using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using QMFrameWork.Common.Encrypt;
using QMFrameWork.Data;
using QMAPP.FJC.DAL.Operation;
using QMAPP.FJC.Entity.Operation;
using QMAPP.BLL;
using QMAPP.Entity;
using QMAPP.FJC.BLL.Dict;
using QMAPP.FJC.BLL.Basic;
using QMAPP.FJC.DAL.Basic;
using QMAPP.FJC.Entity.Basic;
using QMFrameWork.Log;
using QMAPP.FJC.Entity;
using QMAPP.FJC.DAL.FileCopy;
using QMFrameWork.Common.Serialization;
using System.Threading;
using QMAPP.FJC.Entity.ProcessParameter;
//using QMAPP.FJC.DAL.ProcessParameter;
using QMAPP.FJC.DAL;
using QMFrameWork.Common.Task;
using QMAPP.MD.Entity;
namespace QMAPP.FJC.BLL.Operation
{
    /// <summary>
    /// 模块编号:M13-2
    /// 作    用:加工记录
    /// 作    者:单雨春
    /// 编写日期:2015年06月04日
    ///</summary>
    public class MainOperationBLL : BaseBLL
    {

        #region 获取列表
        
        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="condition">条件</param>
        /// <param name="page">数据页</param>
        /// <returns>数据页</returns>
        public DataResult<DataPage> GetListWithParameter(MainOperation condition, DataPage page)
        {
            DataResult<DataPage> dataResult = new DataResult<DataPage>();
            try
            {
                #region 获得加工参数标准值
                var conditionPParameter = new ProcessParameter
                    {
                        //MACHINECODDE = condition.MACHINECODDE,
                        WORKCELL_CODE=condition.WORKCELL_CODE,
                        
                    };
                var listPParameter = new ProcessParameterDAL().GetList(conditionPParameter);
                if (listPParameter == null || listPParameter.Count == 0)
                {
                    dataResult.IsSuccess = false;
                    dataResult.Msg = QMAPP.FJC.Entity.Resource.NotSetProcessParameter;
                    dataResult.Result = new DataPage();
                    dataResult.Result.Result = new DataTable();
                    return dataResult;
                }
                #endregion

                #region 获得加工记录及加工参数
                condition.SelectCollumns = String.Join(",", listPParameter.Select(o => o.PARANAME));
                condition.PARATABLENAME = listPParameter.FirstOrDefault().PARATABLENAME;
                dataResult.Result = new MainOperationDAL().GetListWithParameter(condition, page);

                if (dataResult.Result.Result == null)
                {
                    dataResult.IsSuccess = false;
                    dataResult.Msg = QMAPP.FJC.Entity.Resource.NothingData;
                    dataResult.Result.Result = new DataTable();
                    return dataResult;
                }

                DataTable dtResult = dataResult.Result.Result as DataTable;

                DictManageBLL dictColumnName = new DictManageBLL(DictKind.MAINOPERATIONSEARCHFORM);
                DictManageBLL dictProcessType = new DictManageBLL(DictKind.PROCESSTYPE);
                DictManageBLL dictProductType = new DictManageBLL(DictKind.PRODUCTTYPE);
                DictManageBLL dictLJStatus = new DictManageBLL(DictKind.LJSTATUS);
                DictManageBLL dictOperateState = new DictManageBLL(DictKind.OPERATESTATE);

                IList<DataColumn> listDelColumn = new List<DataColumn>();

                //转换枚举描述
                foreach (DataRow item in dtResult.Rows)
                {
                    item["PROCESSTYPE"] = dictProcessType.GetDictValue(item["PROCESSTYPE"].ToString());
                    item["PRODUCTTYPE"] = dictProductType.GetDictValue(item["PRODUCTTYPE"].ToString());
                    item["STATUS"] = dictLJStatus.GetDictValue(item["STATUS"].ToString());
                    item["OPERATESTATE"] = dictOperateState.GetDictValue(item["OPERATESTATE"].ToString());
                }


                //设置标题
                foreach (var item in dtResult.Columns.Cast<DataColumn>())
                {
                    if (item.ColumnName == "OPERATEDDATESTR" || item.ColumnName == "CREATEDATESTR")
                    {
                        //移除原来datetime类型的OPERATEDDATE、CREATEDATE
                        listDelColumn.Add(item);
                    }
                    else
                    {
                        var strColumnName = dictColumnName.GetDictValue(item.ColumnName);
                        if (string.IsNullOrEmpty(strColumnName))
                        {
                            var entityParam = listPParameter.FirstOrDefault(o => o.PARANAME == item.ColumnName);
                            if (entityParam != null)
                            {
                                strColumnName = entityParam.PARADESCRIBE;
                            }
                        }
                        if (!string.IsNullOrEmpty(strColumnName))
                        {
                            item.ColumnName = strColumnName;
                        }
                        else
                        {
                            listDelColumn.Add(item);
                        }
                    }
                }

                //移除
                foreach (var item in listDelColumn)
                {
                    dtResult.Columns.Remove(item);
                }

                dataResult.IsSuccess = true;
                #endregion
            }
            catch (Exception ex)
            {
                LogManager.LogHelper.Error(new LogInfo()
                {
                    ErrorInfo = ex,
                    Tag = ex.StackTrace,
                    Info = "加工记录-获取列表"
                });
                dataResult.IsSuccess = false;
                dataResult.Msg = Resource.SystemException;
            }
            return dataResult;
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="condition">条件</param>
        /// <param name="page">数据页</param>
        /// <returns>数据页</returns>
        public DataPage GetList(MainOperation condition, DataPage page)
        {
            try
            {
                //获取信息列表
                DataPage dataPage = new MainOperationDAL().GetList(condition, page);

                #region 转换状态
                List<MainOperation> list = dataPage.Result as List<MainOperation>;
                DictManageBLL operationStatusBll = new DictManageBLL(DictKind.OPERATESTATE);
                foreach (MainOperation item in list)
                {
                    //工序类别
                    item.OPERATESTATETEXT = operationStatusBll.GetDictValue(item.OPERATESTATE);
                }
                #endregion
                return dataPage;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public DataPage GetOperationList(MainOperation condition, DataPage page)
        {
            try
            {
                //获取信息列表
                DataPage dataPage = new MainOperationDAL().GetOperationList(condition, page);

                #region 转换状态
                List<MainOperation> list = dataPage.Result as List<MainOperation>;
                DictManageBLL operationStatusBll = new DictManageBLL(DictKind.OPERATESTATE);
                foreach (MainOperation item in list)
                {
                    //工序类别
                    item.OPERATESTATETEXT = operationStatusBll.GetDictValue(item.OPERATESTATE);
                }
                #endregion
                return dataPage;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public DataPage GetOperationListNew(MainOperation condition, DataPage page)
        {
            try
            {
                //获取信息列表
                DataPage dataPage = new MainOperationDAL().GetOperationListNew(condition, page);

                #region 转换状态
                List<MainOperation> list = dataPage.Result as List<MainOperation>;
                DictManageBLL operationStatusBll = new DictManageBLL(DictKind.OPERATESTATE);
                foreach (MainOperation item in list)
                {
                    //工序类别
                    item.OPERATESTATETEXT = operationStatusBll.GetDictValue(item.OPERATESTATE);
                }
                #endregion
                return dataPage;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="condition">条件</param>
        /// <returns>全部数据</returns>
        public List<MainOperation> GetAllList(MainOperation condition)
        {
            try
            {

                List<MainOperation> list = new MainOperationDAL().GetList(condition);
                DictManageBLL operationStatusBll = new DictManageBLL(DictKind.OPERATESTATE);
                DictManageBLL processTypeBll = new DictManageBLL(DictKind.PROCESSTYPE);

                foreach (MainOperation item in list)
                {
                    //工序类别
                    item.OPERATESTATETEXT = operationStatusBll.GetDictValue(item.OPERATESTATE);
                    item.PROCESSTYPETEXT = processTypeBll.GetDictValue(item.PROCESSTYPE);
                }
                return list;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="condition">条件</param>
        /// <returns>全部数据</returns>
        public List<MainOperation> GetOperationRecords(string productcode)
        {
            try
            {

                List<MainOperation> list = new MainOperationDAL().GetOperationRecords(productcode);
                ProcessParameterDAL dal = new ProcessParameterDAL();
                var allparms = dal.GetList(new ProcessParameter { });
                
                foreach (var rd in list)
                {
                    rd.ParamColumns = allparms.Where(p => p.MACHINECODDE == rd.MACHINECODDE).ToList();
                    rd.PARATABLENAME = string.Join(",", rd.ParamColumns.GroupBy(p => p.PARATABLENAME).Select(p => p.Key).ToArray());
                    rd.SelectCollumns = string.Join(",", rd.ParamColumns.Select(p => p.PARANAME).ToArray());
                    if (rd.ParamColumns.Count > 0)
                    {
                        rd.ViewName = rd.ParamColumns.FirstOrDefault().MEMO;
                    }
                }
                
                return list;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 获取列表(用于服务)
        /// </summary>
        /// <param name="condition">条件</param>
        /// <returns>全部数据</returns>
        public List<MainOperation> GetListUsedByCell(MainOperation condition)
        {
            try
            {
                List<MainOperation> list = new MainOperationDAL().GetList(condition);
                return list;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 根据扫描条码获取之前工序下拉列表(返修winform)
        /// </summary>
        /// <param name="condition">条件</param>
        /// <returns>全部数据</returns>
        public List<MainOperation> GetMainOperationWorkCell(string ProductCode, bool isINJECTION)
        {
            try
            {
                List<MainOperation> list = new MainOperationDAL().GetMainOperationWorkCell(ProductCode, isINJECTION);
                return list;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// 获取统计列表
        /// </summary>
        /// <param name="condition">条件</param>
        /// <returns>全部数据</returns>
        public DataResult<DataTable> GetListForstatistic(MainOperation condition)
        {          DataResult<DataTable> dr = new DataResult<DataTable>();
            try
            {
      
               DataTable dt = new MainOperationDAL().GetListForstatistic(condition);
                DictManageBLL operationStatusBll = new DictManageBLL(DictKind.PRODUCTTYPE);

                foreach (DataRow row in dt.Rows)
                {
                    //工序类别
                    row["产品类别"] = operationStatusBll.GetDictValue(row["产品类别"].ToString());
                }
                dr.IsSuccess = true;
                dr.Result = dt;
              
            }
            catch (Exception ex)
            {
                dr.IsSuccess = false;
                dr.Msg = ex.Message;
            } 
            return dr;
        }

        public DataResult<DataTable> GetListForstatisticWithColor(MainOperation condition)
        {
            DataResult<DataTable> dr = new DataResult<DataTable>();
            try
            {

                DataTable dt = new MainOperationDAL().GetListForStatisticWithColor(condition);
                DictManageBLL operationStatusBll = new DictManageBLL(DictKind.PRODUCTTYPE);

                foreach (DataRow row in dt.Rows)
                {
                    //工序类别
                    //row["产品类别"] = operationStatusBll.GetDictValue(row["产品类别"].ToString());
                }
                dr.IsSuccess = true;
                dr.Result = dt;

            }
            catch (Exception ex)
            {
                dr.IsSuccess = false;
                dr.Msg = ex.Message;
            }
            return dr;
        }
        

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="condition">条件</param>
        /// <returns>全部数据</returns>
        public MainOperation GetByCondition(MainOperation condition)
        {
            try
            {
                List<MainOperation> list = new MainOperationDAL().GetList(condition);
                if (list.Count > 0)
                {
                    DictManageBLL operationStatusBll = new DictManageBLL(DictKind.OPERATESTATE);
                    //工序类别
                    list[0].OPERATESTATETEXT = operationStatusBll.GetDictValue(list[0].OPERATESTATE);

                    return list[0];
                }

                return null;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 产品加工追溯

        #region 获取列表
        /// <summary>
        /// 获取列表 
        /// </summary>
        /// <param name="condition">条件</param>
        /// <param name="page">数据页</param>
        /// <returns>数据页</returns>
        public DataResult<DataPage> GetMainOperationReviewList(MainOperation condition, DataPage page)
        {
            DataResult<DataPage> result = new DataResult<DataPage>();
            DataPage dataPage = null;
            try
            {
                if (string.IsNullOrEmpty(condition.PRODUCTCODE)
                    && string.IsNullOrEmpty(condition.MAINCODE)
                    )
                {
                    dataPage = new DataPage();
                    dataPage.Result = new List<MainOperation>();
                    result.Result = dataPage;
                    return result;
                }

                dataPage = new MainOperationDAL().GetMainOperationReviewList(condition, page);

                #region 转换零件类别、物料类别显示类型
                List<MainOperation> machineInfoList = dataPage.Result as List<MainOperation>;

                DictManageBLL dictProductStatusBll = new DictManageBLL(DictKind.PRODUCTSTATUS);
                DictManageBLL dictProcessStatusBll = new DictManageBLL(DictKind.PROCESSSTATUS);
                DictManageBLL dictProcessTypeBll = new DictManageBLL(DictKind.PROCESSTYPE);

                foreach (MainOperation m in machineInfoList)
                {
                    //产品状态
                    m.STATUS = dictProductStatusBll.GetDictValue(m.STATUS);
                    //加工状态
                    m.OPERATESTATE = dictProcessStatusBll.GetDictValue(m.OPERATESTATE);
                    //工序类别
                    m.CURRENTPROCESS = dictProcessTypeBll.GetDictValue(m.CURRENTPROCESS);
                }
                #endregion

                result.Result = dataPage;
            }
            catch (Exception ex)
            {
                LogManager.LogHelper.Error(new LogInfo()
                {
                    ErrorInfo = ex,
                    Tag = ex.StackTrace,
                    Info = "加工记录逻辑层-产品加工追溯获取列表!"
                });
                result.IsSuccess = false;
                result.Msg = Resource.SystemException;
                throw ex;
            }
            result.IsSuccess = true;
            return result;
        }
        public List<Product> GetMainOperations(Product condition)
        {
            //DataPage dataPage = new DataPage();
            //var desult = new List<ProductInjection>();
            //DataResult<DataPage> result = new DataResult<DataPage>();
            MainBLL mb = new MainBLL();
            try
            {
                if (string.IsNullOrEmpty(condition.PRODUCTCODE))
                {
                    if (string.IsNullOrEmpty(condition.MAINCODE))
                    {
                        return null;
                    }
                    
                    var m = mb.GetByCondition(new Main { publicCode = condition.MAINCODE });
                    if (m == null)
                    {
                        return null;
                    }
                    condition.PRODUCTCODE = m.EPIDERMISCODE;
                }


                List<Product> machineInfoList = new MainOperationDAL().GetMainOperations(condition);

                #region 转换零件类别、物料类别显示类型

                DictManageBLL dictProductStatusBll = new DictManageBLL(DictKind.PRODUCTSTATUS);
                DictManageBLL dictProcessStatusBll = new DictManageBLL(DictKind.PROCESSSTATUS);
                DictManageBLL dictProcessTypeBll = new DictManageBLL(DictKind.PROCESSTYPE);

                //foreach (Product m in machineInfoList)
                //{
                //    //产品条码
                //    m.PRODUCTCODE = condition.PRODUCTCODE;
                //    //总成条码
                //    var main = mb.GetByCondition(new Main { publicCode = condition.PRODUCTCODE });
                //    if (main != null)
                //    {
                //        m.MAINCODE = condition.MAINCODE;
                //    }
                //    m.CREATEDATESTR = m.OPERATEDDATE.ToString("yyyy-MM-dd HH:mm:ss");
                //    //产品状态
                //    m.STATUS = dictProductStatusBll.GetDictValue(m.STATUS);
                //    //加工状态
                //    m.OPERATESTATE = dictProcessStatusBll.GetDictValue(m.OPERATESTATE);
                //    //工序类别
                //    m.CURRENTPROCESS = dictProcessTypeBll.GetDictValue(m.CURRENTPROCESS);
                //}
                #endregion

                //result.Result = dataPage;
                //result.IsSuccess = true;
                return machineInfoList;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 导出数据
        /// <summary>
        /// 获取导出的数据
        /// </summary>
        /// <param name="user">查询条件</param>
        /// <returns>数据</returns>
        public DataResult<DataTable> GetExportDataForMOR(MainOperation model)
        {
            DataResult<DataTable> result = new DataResult<DataTable>();
            try
            {
                DataTable dt = new MainOperationDAL().GetExportDataForMOR(model);

                #region 转换零件类别、物料类别显示类型
                DictManageBLL dictProductStatusBll = new DictManageBLL(DictKind.PRODUCTSTATUS);
                DictManageBLL dictProcessStatusBll = new DictManageBLL(DictKind.PROCESSSTATUS);
                DictManageBLL dictProcessTypeBll = new DictManageBLL(DictKind.PROCESSTYPE);

                foreach (DataRow item in dt.Rows)
                {
                    //产品状态
                    item["STATUS"] = dictProductStatusBll.GetDictValue(item["STATUS"].ToString());
                    //加工状态
                    item["OPERATESTATE"] = dictProcessStatusBll.GetDictValue(item["OPERATESTATE"].ToString());
                    //工序类别
                    item["CURRENTPROCESS"] = dictProcessTypeBll.GetDictValue(item["CURRENTPROCESS"].ToString());
                }
                #endregion

                result.Result = dt;
            }
            catch (Exception ex)
            {
                LogManager.LogHelper.Error(new LogInfo()
                {
                    ErrorInfo = ex,
                    Tag = ex.StackTrace,
                    Info = "加工记录逻辑层-产品加工追溯获取导出数据!"
                });
                result.IsSuccess = false;
                result.Msg = Resource.SystemException;
                throw ex;
            }
            result.IsSuccess = true;
            return result;
        }
        public DataResult<DataTable> GetExportDataForMORNew(MainOperation model)
        {
            DataResult<DataTable> result = new DataResult<DataTable>();
            try
            {
                MainBLL mb = new MainBLL();
                if (string.IsNullOrEmpty(model.PRODUCTCODE))
                {
                    if (string.IsNullOrEmpty(model.MAINCODE))
                    {
                        return null;
                    }

                    var m = mb.GetByCondition(new Main { publicCode = model.MAINCODE });
                    if (m == null)
                    {
                        return null;
                    }
                    model.PRODUCTCODE = m.EPIDERMISCODE;
                }


                //List<MainOperation> machineInfoList = new MainOperationDAL().GetMainOperations(condition);

                DataTable dt = new MainOperationDAL().GetExportDataForMORNew(model);

                #region 转换零件类别、物料类别显示类型
                DictManageBLL dictProductStatusBll = new DictManageBLL(DictKind.PRODUCTSTATUS);
                DictManageBLL dictProcessStatusBll = new DictManageBLL(DictKind.PROCESSSTATUS);
                DictManageBLL dictProcessTypeBll = new DictManageBLL(DictKind.PROCESSTYPE);

                foreach (DataRow item in dt.Rows)
                {
                    //产品条码
                    item["PRODUCTCODE"] = model.PRODUCTCODE;
                    //总成条码
                    //var main = mb.GetByCondition(new Main { publicCode = model.PRODUCTCODE });
                    //if (main != null)
                    //{
                    //    item["MAINCODE"] = model.MAINCODE;
                    //}
                    //item["CREATEDATESTR"] = item["OPERATEDDATE"].ToString("yyyy-MM-dd HH:mm:ss");

                    //产品状态
                    item["STATUS"] = dictProductStatusBll.GetDictValue(item["STATUS"].ToString());
                    //加工状态
                    item["OPERATESTATE"] = dictProcessStatusBll.GetDictValue(item["OPERATESTATE"].ToString());
                    //工序类别
                    item["CURRENTPROCESS"] = dictProcessTypeBll.GetDictValue(item["CURRENTPROCESS"].ToString());
                }
                #endregion

                result.Result = dt;
            }
            catch (Exception ex)
            {
                LogManager.LogHelper.Error(new LogInfo()
                {
                    ErrorInfo = ex,
                    Tag = ex.StackTrace,
                    Info = "加工记录逻辑层-产品加工追溯获取导出数据!"
                });
                result.IsSuccess = false;
                result.Msg = Resource.SystemException;
                throw ex;
            }
            result.IsSuccess = true;
            return result;
        }
        #endregion

        #endregion


        #region 设备加工

        /// <summary>
        /// 判断是否符合设备模具的加工条件
        /// </summary>
        /// <param name="operationServiceParam"></param>
        /// <returns></returns>
        public DataResult GetMashineStatus(OperationServiceParam operationServiceParam)
        {
            DataResult result = new DataResult();
            string modelStation = "1";//默认第一个模具
            //设置当前设备的当前模具
            if (string.IsNullOrEmpty(operationServiceParam.machineInfo.MOLDNUMBER))
            {
                operationServiceParam.machineInfo.MOLDNUMBER = modelStation;
            }

            //如果设备存在位置扫描标示
            if (operationServiceParam.machineInfo.ISSTATION.Equals(EnumGeter.HAVEORNOT.HAVE.GetHashCode()))
            {
                #region 调用接口------获取当前的模具位置
                List<MachineInfoModels> models = operationServiceParam.machineInfo.MODELS;//设备模具列表
                if (models != null && models.Count > 0)//证明有多模具,而且需要获取模具
                {
                    //modelStation = "";//调用接口获取当前模具位置
                    //算出当前放零件的位置
                    modelStation = ((Convert.ToInt32(modelStation) + operationServiceParam.machineInfo.MODELSTATIONS) % models.Count).ToString();
                    operationServiceParam.model = models.Find(m => m.MODELSTATION == modelStation);
                }
                #endregion
            }


            result.IsSuccess = true;
            return result;
        }


        /// <summary>
        /// 处理零件条码返回零件实体
        /// </summary>
        /// <param name="productCode">零件条码</param>
        /// <param name="operationServiceParam">传递参数</param>
        /// <returns>Product--result.IsMain=true当前零件为本体 result.IsMain==false为零件</returns>
        public DataResult<Product> ExplainProduct(string productCode, OperationServiceParam operationServiceParam)
        {
            DataResult<Product> result = new DataResult<Product>();
            Product product = new Product();
            try
            {
                #region 1.判断是否重复扫描,重复扫描不做任何操作
                int exsitCount = operationServiceParam.productList.FindAll(m => m.PRODUCTCODE == productCode).Count;
                if (exsitCount > 0)
                {
                    result.IsSuccess = false;
                    return result;
                }
                #endregion

                #region 2.获取当前零件信息
                Product proSearchModel = new Product();
                proSearchModel.PRODUCTCODE = productCode;

                //获取产品信息
                List<Product> products = new ProductBLL().GetListAndAttrByCondition(proSearchModel).OrderBy(o => o.USINGSTATE).ToList<Product>();
                
                //如果产品数量大于1,那么一定风道信息
                if (products.Count > 1)
                {
                    //这里需要额外处理一下

                    //正常先获取处于本工位的条码信息
                    product = products.Find(m => m.CURRENTPROCESS == operationServiceParam.processSet.PROCESSTYPE);

                    //红外焊接工位处理
                    if (operationServiceParam.processSet.PROCESSTYPE == EnumGeter.ProcessType.hongwaihanjie.GetHashCode().ToString())
                    {
                        //获取红外焊接工位未使用的风道
                        product = products.Find(m => 
                            m.USINGSTATE == EnumGeter.USINGSTATE.UNUSED.GetHashCode().ToString() 
                            && m.CURRENTPROCESS == operationServiceParam.processSet.PROCESSTYPE);

                        //获取铆接工位未使用的风道
                        if (product == null)
                        {
                            product = products.Find(m =>
                            m.USINGSTATE == EnumGeter.USINGSTATE.UNUSED.GetHashCode().ToString());
                        }
                    }

                    //如果前面的条件过滤了所有的条码信息,表示在铆接和红外焊接的工序两个风道都使用完成
                    if (product == null)
                    {
                        product = products[0];
                    }
                }
                else if (products.Count == 1)
                {
                    product = products[0];


                    if (operationServiceParam.machineInfo.PROCESSTYPE
                         == EnumGeter.ProcessType.maojie.GetHashCode().ToString()
                         && product.CURRENTPROCESS != EnumGeter.ProcessType.maojie.GetHashCode().ToString()
                         && productCode.IndexOf("B9B") == 0)
                    {
                        //20160612不全注塑丢失的条码信息
                        //闫永刚
                        product = InsertProductBack(productCode, operationServiceParam);
                    }

                    //2016-7-3 当红外焊接设备扫描了风道时,并且该风道已经使用,这时不能提升该风道已经使用
                    //因为两个风道使用同一个码,应提提示该风道没有进行铆接操作
                    //闫永刚
                    if (operationServiceParam.machineInfo.PROCESSTYPE
                        == EnumGeter.ProcessType.hongwaihanjie.GetHashCode().ToString()
                        && product.USINGSTATE == EnumGeter.USINGSTATE.USED.GetHashCode().ToString()
                        && productCode.IndexOf("B9B") == 0)
                    {
                        result.IsSuccess = false;
                        result.Msg = string.Format("{0}未进行铆接操作!", product.PRODUCTCODE);
                        return result;
                    }
                    

                }
                else
                {
                    product = null;

                    //20160612不全注塑丢失的条码信息
                    //闫永刚
                    product = InsertProductBack(productCode, operationServiceParam);
                }

                #endregion

                if (product != null)
                {
                    product.productBasic = new ProductBasicBLL().GetByCode(new ProductBasic { PRODUCTTYPE = product.PRODUCTTYPE });
                }

                #region 2.1 如果不存在当前零件信息,那么判断是否为外购件,并添加外购件信息
                if (product == null)
                {

                    //如果未外购件则添加
                    //根据条码调取服务获得该条码对应的类别
                    /////////服务
                    ProductBasic proBasic = new ProductBasic();
                    proBasic.PRODUCTTYPE = "";
                    if (productCode.IndexOf("B9H") == 0)//左格栅
                    {
                        proBasic.PRODUCTTYPE = "6";

                        if (productCode.Length != 18)
                        {
                            result.IsSuccess = false;
                            result.Msg = productCode + "左格栅条码格式错误!\r\n请扫描正确的左格栅条码!";
                            return result;
                        }
                        string colorCode=productCode.Substring(12,3);

                        if (colorCode != "24A" && colorCode != "6PS"
                            && colorCode != "RK1" && colorCode != "AY2")
                        {
                            result.IsSuccess = false;
                            result.Msg = productCode + "左格栅条码颜色信息错误!\r\n请扫描正确的左格栅条码!";
                            return result;
                        }
                    }
                    else if (productCode.IndexOf("B9I") == 0)//右格栅
                    {
                        proBasic.PRODUCTTYPE = "10";

                        if (productCode.Length != 18)
                        {
                            result.IsSuccess = false;
                            result.Msg = productCode + "右格栅条码格式错误!\r\n请扫描正确的右格栅条码!";
                            return result;
                        }

                        string colorCode = productCode.Substring(12, 3);

                        if (colorCode != "24A" && colorCode != "6PS"
                            && colorCode != "RK1" && colorCode != "AY2")
                        {
                            result.IsSuccess = false;
                            result.Msg = productCode + "右格栅条码颜色信息错误!\r\n请扫描正确的右格栅条码!";
                            return result;
                        }
                    }
                    else if (productCode.IndexOf("B9J") == 0)//中控支架
                    {
                        proBasic.PRODUCTTYPE = "7";
                    }
                    else if (productCode.IndexOf("B9K") == 0)//HUD支架
                    {
                        proBasic.PRODUCTTYPE = "11";

                        if (productCode.Length != 18)
                        {
                            result.IsSuccess = false;
                            result.Msg = productCode + "HUD支架条码格式错误!\r\n请扫描正确的HUD支架式条码!";
                            return result;
                        }
                    }
                    else
                    {
                        result.IsSuccess = false;
                        result.Msg = Resource.OperationProNotFound;
                        return result;
                    }


                    proBasic = new ProductBasicBLL().GetByCode(proBasic);
                    //获取类别出错
                    if (proBasic == null)
                    {
                        result.Msg = Resource.OperationProTypeError;
                        result.IsSuccess = false;
                        return result;
                    }

                    //获取判断出该条码属于哪个类别
                    #region 自制件
                    if (proBasic.PRODUCTSOURCE.Equals(EnumGeter.PRODUCTSOURCE.SELFMADE.GetHashCode().ToString()))//属于自制
                    {
                        //判断当前设备是否接受和发送指令
                        if (!operationServiceParam.machineInfo.ISCONTROL.Equals(EnumGeter.ISCONTROL.NOSENDNOREAD.GetHashCode().ToString()))
                        {
                            result.Msg = Resource.OperationProNotFound;
                            result.IsSuccess = false;
                            return result;
                        }

                        //只有设备既不接受指令也不发送指令才需要添加

                        //获取当前零件类别的工序设置的第一道工序
                        ProcessSet processSet = new ProcessSetBLL().GetByModel(new ProcessSet { PRODUCTTYPE = proBasic.PRODUCTTYPE, PROCESSINDEX = 1 }).Result;
                        //将当前零件插入零件条码表生成原始记录
                        Product recorder = new Product();
                        recorder.PRODUCTCODE = productCode;
                        recorder.PRODUCTSOURCE = EnumGeter.PRODUCTSOURCE.SELFMADE.GetHashCode().ToString();
                        recorder.PRODUCTTYPE = proBasic.PRODUCTTYPE;
                        recorder.STATUS = EnumGeter.PRODUCTSTAUTS.QUALIFIED.GetHashCode().ToString();
                        recorder.CURRENTPROCESS = processSet.PROCESSTYPE;
                        recorder.PRODUCELINE = EnumGeter.PRODUCELINE.B9.ToString();
                        recorder.OUTFLAG = EnumGeter.PRODUCTOUTFLAG.INLIBRARY.GetHashCode().ToString();
                        recorder.USINGSTATE = EnumGeter.PRODUCTUSESTATE.UNUSED.GetHashCode().ToString();
                        recorder.CAPACITY = 1;
                        recorder.USINGCOUNT = 0;

                        //如果为表皮的话需要拆解表皮属性
                        if (recorder.PRODUCTTYPE.Equals(EnumGeter.ProductType.biaopi.GetHashCode().ToString()))
                        {
                            //解析条码
                            ProductAttribute productAttribute = new ProductAttribute();
                            //搪塑机编号
                            productAttribute.VAL1 = productCode.Substring(10, 7);
                            //产品类型
                            productAttribute.VAL2 = productCode.Substring(17, 2);
                            //高低配
                            productAttribute.VAL3 = productCode.Substring(19, 1);
                            //颜色
                            productAttribute.VAL4 = productCode.Substring(20, 1);
                            //腔
                            productAttribute.VAL5 = productCode.Substring(21, 1);
                            //模腔
                            productAttribute.VAL6 = productCode.Substring(22);
                            //加工日期
                            productAttribute.VAL7 = DateTime.ParseExact(productCode.Substring(0, 10), "yyMMddHHmm", System.Globalization.CultureInfo.CurrentCulture).ToString("yyyy-MM-dd");

                            DataResult resultInsert = new ProductBLL().InsertEpidermis(recorder);
                            if (resultInsert.IsSuccess == false)
                            {
                                result.Msg = Resource.OperationProNotFound;
                                result.IsSuccess = false;
                                return result;
                            }

                        }
                        else
                        {
                            DataResult resultInsert = new ProductBLL().Insert(recorder);
                            if (resultInsert.IsSuccess == false)
                            {
                                result.Msg = Resource.OperationProNotFound;
                                result.IsSuccess = false;
                                return result;
                            }
                        }

                        product = new ProductBLL().GetAndAttrByCondition(proSearchModel);
                        result.Result = product;
                        result.IsSuccess = true;
                    }
                    #endregion

                    #region 采购件
                    if (proBasic.PRODUCTSOURCE.Equals(EnumGeter.PRODUCTSOURCE.OUTSOURCING.GetHashCode().ToString()))//属于采购
                    {
                        Product pAdd = new Product();
                        pAdd.PRODUCTTYPE = proBasic.PRODUCTTYPE;
                        pAdd.PRODUCTCODE = productCode;
                        pAdd.PRODUCTSOURCE = EnumGeter.PRODUCTSOURCE.OUTSOURCING.GetHashCode().ToString();
                        pAdd.MACHINENAME = operationServiceParam.machineInfo.MACHINENAME;
                        pAdd.MACHINECODDE = operationServiceParam.machineInfo.MACHINECODDE;
                        pAdd.STATUS = EnumGeter.PRODUCTSTAUTS.QUALIFIED.GetHashCode().ToString();
                        pAdd.CURRENTPROCESS = operationServiceParam.processSet.PROCESSTYPE;
                        pAdd.PRODUCELINE = EnumGeter.PRODUCELINE.B9.ToString();
                        pAdd.PRODUCESHIFTTCODE = "";
                        pAdd.PRODUCESHIFTNAME = "";
                        pAdd.OUTFLAG = EnumGeter.PRODUCTOUTFLAG.INLIBRARY.GetHashCode().ToString();
                        pAdd.USINGSTATE = EnumGeter.PRODUCTUSESTATE.USING.GetHashCode().ToString();
                        pAdd.CAPACITY = proBasic.CAPATITY;
                        pAdd.USINGCOUNT = 0;


                        //调用保存接口
                        DataResult<Product> resultInsert = new ProductBLL().InsertAndReturn(pAdd);

                        //保存成功
                        if (!resultInsert.IsSuccess)
                        {
                            result.Msg = resultInsert.Msg;
                            result.IsSuccess = false;
                            return result;
                        }

                        product = resultInsert.Result;
                        product.productBasic = proBasic;
                    }
                    #endregion
                }
                #endregion

                #region 2.2 设置零件是哪种类别本体还是零件

                if (product.PRODUCTTYPE.Equals(EnumGeter.ProductType.biaopi.GetHashCode().ToString())
                    && product.USINGSTATE.Equals(EnumGeter.USINGSTATE.USED.GetHashCode().ToString())
                    && operationServiceParam.machineInfo.PROCESSTYPE!=EnumGeter.ProcessType.lengdaoruohua.GetHashCode().ToString()
                    )
                {
                    product.IsMain = true; //该零件为本体
                }
                else
                {
                    product.IsMain = false;//该零件为零件
                }

                #region
                result.Result = product;
                result.IsSuccess = true;
            }
            catch (Exception ex)
            {
                result.IsSuccess = false;
                result.Msg = ex.Message;
                throw;
            }

            return result;
        }

        /// <summary>
        /// 插入注塑产品信息
        /// </summary>
        /// <param name="productCode"></param>
        /// <param name="operationServiceParam"></param>
        /// <returns></returns>
        public Product InsertProductBack(string productCode,OperationServiceParam operationServiceParam)
        {
            Product product = null;

            if (productCode.IndexOf("B9A") == 0 || productCode.IndexOf("B9B") == 0 
                || productCode.IndexOf("B9C") == 0 || productCode.IndexOf("FJC") == 0
                || productCode.IndexOf("AAA") == 0)
            {
               

                Product newRecorder = new Product();
                newRecorder.PID = Guid.NewGuid().ToString();
                newRecorder.PRODUCTCODE = productCode;
                newRecorder.PRODUCTSOURCE = EnumGeter.PRODUCTSOURCE.SELFMADE.GetHashCode().ToString();
                newRecorder.STATUS = EnumGeter.PRODUCTSTAUTS.QUALIFIED.GetHashCode().ToString();
                newRecorder.CURRENTPROCESS = "";
                newRecorder.PRODUCELINE = EnumGeter.PRODUCELINE.B9.ToString();
                newRecorder.OUTFLAG = EnumGeter.PRODUCTOUTFLAG.INLIBRARY.GetHashCode().ToString();
                newRecorder.USINGSTATE = EnumGeter.PRODUCTUSESTATE.UNUSED.GetHashCode().ToString();
                newRecorder.CAPACITY = 1;
                newRecorder.USINGCOUNT = 0;
                newRecorder.CURRENTPROCESS = operationServiceParam.processSet.PROCESSTYPE;


                #region 初始化零件号
                //获取产品零件号

                List<MaterialCodeInit> initList = new MaterialCodeInitDAL().GetList(new MaterialCodeInit() { PRODUCT_TYPES = productCode.Substring(0,3) });
                if (initList.Count > 0)
                {
                    MaterialCodeInit init = initList[0];
                    newRecorder.WORKCELL_CODE = init.WORKCELL_CODE;
                    newRecorder.WORKCENTER_CODE = init.WORKCENTER_CODE;
                    newRecorder.MATERIAL_CODE = init.MATERIAL_CODE;
                    newRecorder.WORKLOC_CODE = init.WORKLOC_CODE;
                    newRecorder.MATERIAL_TYPE = init.MATERIAL_TYPE;
                }

                #endregion

                InsertInjectProduct(newRecorder);


                List<Product> proList = new ProductBLL().GetListAndAttrByCondition(newRecorder);
                product = proList[0];

                #endregion
            }

            return product;
        }
        

        #region 插入注塑产品信息及加工记录

        //插入产品记录
        //插入注塑加工记录
        private void InsertInjectProduct(Product newRecorder)
        {

            try
            {
                DateTime dt = Convert.ToDateTime("20" + newRecorder.PRODUCTCODE.Substring(3, 2) + "-" + newRecorder.PRODUCTCODE.Substring(5, 2) + "-" + newRecorder.PRODUCTCODE.Substring(7, 2) + " " + newRecorder.PRODUCTCODE.Substring(9, 2) + ":" + newRecorder.PRODUCTCODE.Substring(11, 2) + ":00");
                newRecorder.CREATEDATE = dt;
                MainOperation main = new MainOperation();
                main.PID = Guid.NewGuid().ToString();
                main.PDID = newRecorder.PID;
                main.PRODUCTCODE = newRecorder.PRODUCTCODE;
              
                if (newRecorder.PRODUCTCODE.IndexOf("B9A") == 0)
                {
                    main.PROCESSTYPE = EnumGeter.ProcessType.gujiazhusu.GetHashCode().ToString();
                    main.CURRENTPROCESS = EnumGeter.ProcessType.gujiazhusu.GetHashCode().ToString();
                    newRecorder.PRODUCTTYPE = EnumGeter.ProductType.gujia.GetHashCode().ToString();
                }
                if (newRecorder.PRODUCTCODE.IndexOf("B9B") == 0)
                {
                    main.PROCESSTYPE = EnumGeter.ProcessType.fengdaozhusu.GetHashCode().ToString();
                    main.CURRENTPROCESS = EnumGeter.ProcessType.fengdaozhusu.GetHashCode().ToString();
                    newRecorder.PRODUCTTYPE = EnumGeter.ProductType.fengdao.GetHashCode().ToString();
                
                }
                if (newRecorder.PRODUCTCODE.IndexOf("B9C") == 0)
                {
                    main.PROCESSTYPE = EnumGeter.ProcessType.HUDfengdaozhusu.GetHashCode().ToString();
                    main.CURRENTPROCESS = EnumGeter.ProcessType.HUDfengdaozhusu.GetHashCode().ToString();
                    newRecorder.PRODUCTTYPE = EnumGeter.ProductType.HUDfengdao.GetHashCode().ToString();

                }

                if (newRecorder.PRODUCTCODE.IndexOf("FJC") == 0)
                {
                    main.PROCESSTYPE = EnumGeter.ProcessType.qinangzhijiazhusu.GetHashCode().ToString();
                    main.CURRENTPROCESS = EnumGeter.ProcessType.qinangzhijiazhusu.GetHashCode().ToString();
                    newRecorder.PRODUCTTYPE = EnumGeter.ProductType.qinangzhijia.GetHashCode().ToString();

                }

                if (newRecorder.PRODUCTCODE.IndexOf("AAA") == 0)
                {
                    main.PROCESSTYPE = EnumGeter.ProcessType.qinangzhijiazhusu.GetHashCode().ToString();
                    main.CURRENTPROCESS = EnumGeter.ProcessType.qinangzhijiazhusu.GetHashCode().ToString();
                    newRecorder.PRODUCTTYPE = EnumGeter.ProductType.qinangzhijia.GetHashCode().ToString();

                }
                
                main.PRODUCTTYPE = newRecorder.PRODUCTTYPE;
                
                main.STATUS = "0";
                main.OPERATESTATE = EnumGeter.OPERATESTATE.COMPLETED.GetHashCode().ToString();
                main.OPERATEDDATE = dt;
                
                main.PRODUCELINE = "B9";
                main.CREATEDATE = dt;

                //InjectionParameterSampleDAL sampleDal = new InjectionParameterSampleDAL();
                InJectionParameter para = new InJectionParameter();
                //para = sampleDal.GetInJectionParameterSample(newRecorder);
                para.PID = Guid.NewGuid().ToString();
                para.PDID = newRecorder.PID;
                para.MOID = main.PID;
                para.PRODUCTCODE = newRecorder.PRODUCTCODE;
                para.CREATEDATE = dt;
                para.OPERATEDATE = dt;
                //para.EDATE = dt.ToString("yyyy-MM-dd HH:mm:ss");

                newRecorder.MACHINECODDE = para.MACHINECODDE;
                newRecorder.MACHINENAME = para.MACHINENAME;

                main.MACHINECODDE = para.MACHINECODDE;
                main.MACHINENAME = para.MACHINENAME;

                MainOperationDAL modal = new MainOperationDAL();
                ProductDAL prodal = new ProductDAL();

                ////InjectionParameterDAL ipdal = new InjectionParameterDAL();

                using (IDataSession session = AppDataFactory.CreateMainSession())
                {
                    //ipdal.BaseSession = session;
                    prodal.BaseSession = session;
                    modal.BaseSession = session;

                    session.OpenTs();

                    prodal.Insert(newRecorder);

                    modal.Insert(main);

                    //ipdal.Insert(para);

                    session.CommitTs();
                }
            }
            catch (Exception ex)
            {
                
                throw;
            }
            

        }

        #endregion

        /// <summary>
        /// 校验零件
        /// </summary>
        /// <param name="product"></param>
        /// <returns>BackStatus=true 代表 Main、 BackStatus=false 代表 Product</returns>
        public DataResult<object> ValidateProudct(Product product)
        {
            DataResult<object> result = new DataResult<object>();
            try
            {


                if (product.IsMain) //当前零件是本体
                {
                    #region 1.获取本体信息
                    Main mainSearchModel = new Main();
                    mainSearchModel.EPIDERMISCODE = product.PRODUCTCODE;
                    List<Main> mainList = new MainBLL().GetAllList(mainSearchModel);
                    if (mainList.Count <= 0)
                    {
                        result.Msg = Resource.OperationMainNotFound;
                        result.IsSuccess = false;
                        return result;
                    }
                    Main main = mainList[0];

                    #region 2.校验出库状态  PROCESSSTATE
                    if (!main.OUTFLAG.Equals(EnumGeter.OUTFLAG.INWAREHOUSE.GetHashCode().ToString()))
                    {
                        result.Msg = "该本体已出库!";
                        result.IsSuccess = false;
                        return result;
                    }
                    #endregion
                    //判断加工状态

                    List<MainOperation> excuteList = this.GetAllList(new MainOperation { PDID = main.PID, OPERATESTATE = EnumGeter.OPERATESTATE.OPERATING.GetHashCode().ToString() });
                    if (excuteList.Count > 0)
                    {
                        result.Msg = excuteList[0].PRODUCTCODE + "正在" + excuteList[0].PROCESSTYPETEXT + "工序加工中!";
                        result.IsSuccess = false;
                        return result;
                    }
                    //获取当前工序内容

                    main.processSets = new ProcessSetBLL().GetListByModel(new ProcessSet { PRODUCTTYPE = EnumGeter.ProductType.benti.GetHashCode().ToString() }).Result;

                    main.processSet = new ProcessSetBLL().GetByModel(new ProcessSet { PRODUCTTYPE = EnumGeter.ProductType.benti.GetHashCode().ToString(),PROCESSTYPE = main.CURRENTPROCESS}).Result;
                   
                    #endregion

                    #region 2.校验加工状态  PROCESSSTATE
                    if (main.PROCESSSTATE.Equals(EnumGeter.OPERATIONSTATE.PROCESSED.GetHashCode().ToString()))
                    {
                        result.Msg = Resource.OperationProductProcessing;
                        result.IsSuccess = false;
                        return result;
                    }
  

                    #endregion

                    #region 3.校验是否合格 STATUS
                    if (!main.STATUS.Equals(EnumGeter.PRODUCTSTAUTS.QUALIFIED.GetHashCode().ToString()))
                    {
                        result.Msg = Resource.OperationProductNotQualified;
                        result.IsSuccess = false;
                        return result;
                    }
                    #endregion


                    #region 5.校验当前本体是否加工已经完成 COMPLETEFLAG
                    if (main.COMPLETEFLAG.Equals(EnumGeter.COMPLETEFLAG.COMPLETED.GetHashCode().ToString()))
                    {
                        result.Msg = Resource.OperatProductComplete;
                        result.IsSuccess = false;
                        return result;
                    }
                    #endregion

                    result.IsSuccess = true;
                    result.BackStatus = true;
                    result.Result = main;

                }


                if (!product.IsMain)//当前零件为零件
                {
                    #region 2.校验出库状态  PROCESSSTATE
                    if (!product.OUTFLAG.Equals(EnumGeter.OUTFLAG.INWAREHOUSE.GetHashCode().ToString()))
                    {
                        result.Msg = "该零件已出库!";
                        result.IsSuccess = false;
                        return result;
                    }
                    #endregion
                    //判断加工状态
                    List<MainOperation> excuteList = this.GetAllList(new MainOperation { PDID = product.PID, OPERATESTATE = EnumGeter.OPERATESTATE.OPERATING.GetHashCode().ToString() });

                    if (excuteList.Count > 0)
                    {
                        result.Msg = excuteList[0].PRODUCTCODE + "正在" + excuteList[0].PROCESSTYPETEXT + "工序加工中!";
                        result.IsSuccess = false;
                        return result;
                    }

                    product.processSets = new ProcessSetBLL().GetListByModel(new ProcessSet { PRODUCTTYPE = product.PRODUCTTYPE}).Result;

                    //获取当前工序内容
                    product.processSet = new ProcessSetBLL().GetByModel(new ProcessSet { PRODUCTTYPE = product.PRODUCTTYPE, PROCESSTYPE = product.CURRENTPROCESS}).Result;
                  
                    #region 1.校验零件是否已经被使用 USINGSTATE
                    if (product.USINGSTATE.Equals(EnumGeter.PRODUCTUSESTATE.USED.GetHashCode().ToString()))
                    {
                        result.Msg = Resource.OperationProductUsed;
                        result.IsSuccess = false;
                        return result;
                    }
                    #endregion

                    #region 2.校验零件是否合格 STATUS
                    if (!product.STATUS.Equals(EnumGeter.PRODUCTSTAUTS.QUALIFIED.GetHashCode().ToString()))
                    {
                        result.Msg = Resource.OperationProductNotQualified;
                        result.IsSuccess = false;
                        return result;
                    }
                    #endregion



                    result.IsSuccess = true;
                    result.BackStatus = false;
                    result.Result = product;
                }
            }
            catch (Exception ex)
            {
                result.IsSuccess = false;
                result.Msg = ex.Message;
                throw;
            }

            return result;
        }

        public DataResult<OperationServiceParam> ValidateProudct(Product product, OperationServiceParam operationServiceParam)
        {
            DataResult<OperationServiceParam> result = new DataResult<OperationServiceParam>();
            try
            {


                if (product.IsMain) //当前零件是本体
                {
                    #region 1.获取本体信息
                    Main mainSearchModel = new Main();
                    mainSearchModel.EPIDERMISCODE = product.PRODUCTCODE;
                    List<Main> mainList = new MainBLL().GetAllList(mainSearchModel);
                    if (mainList.Count <= 0)
                    {
                        result.Msg = Resource.OperationMainNotFound;
                        result.IsSuccess = false;
                        return result;
                    }
                    Main main = mainList[0];

                    #region 2.校验出库状态  PROCESSSTATE
                    if (!main.OUTFLAG.Equals(EnumGeter.OUTFLAG.INWAREHOUSE.GetHashCode().ToString()))
                    {
                        result.Msg = "该本体已出库!";
                        result.IsSuccess = false;
                        return result;
                    }
                    #endregion
                    //判断加工状态

                    List<MainOperation> excuteList = this.GetAllList(new MainOperation { PDID = main.PID });
                    operationServiceParam.moList = excuteList;
                    if (excuteList.Count(o => o.OPERATESTATE == EnumGeter.OPERATESTATE.OPERATING.GetHashCode().ToString()) > 0)
                    {
                        MainOperation priorMo = excuteList.First(o => o.OPERATESTATE == EnumGeter.OPERATESTATE.OPERATING.GetHashCode().ToString());

                        //2016-11-13冲切设备出现不返回加工完成信号的情况
                        //将自动放行从冲切调整成在铣削方位放行
                        if (operationServiceParam.machineInfo.PROCESSTYPE == EnumGeter.ProcessType.xixiao.GetHashCode().ToString()
                            && priorMo.PROCESSTYPE == EnumGeter.ProcessType.chongqie.GetHashCode().ToString())
                        {
                            DataResult res = SetPunchingPassProcess(new Main() { PID = main.PID });

                            result.IsSuccess = false;
                            result.Msg = res.Msg;
                            return result;
                        }
                        else
                        {
                            result.Msg = priorMo.PRODUCTCODE + "正在" + priorMo.PROCESSTYPETEXT + "工序进行加工!\r\n";
                            result.Msg += "请等待加工完成或是手动放行!";
                            result.IsSuccess = false;
                            return result;
                        }

                       
                    }
                    //获取当前工序内容

                    main.processSets = new ProcessSetBLL().GetListByModel(new ProcessSet { PRODUCTTYPE = EnumGeter.ProductType.benti.GetHashCode().ToString() }).Result;

                    main.processSet = new ProcessSetBLL().GetByModel(new ProcessSet { PRODUCTTYPE = EnumGeter.ProductType.benti.GetHashCode().ToString(), PROCESSTYPE = main.CURRENTPROCESS }).Result;

                    #endregion

                    #region 2.校验加工状态  PROCESSSTATE
                    if (main.PROCESSSTATE.Equals(EnumGeter.OPERATIONSTATE.PROCESSED.GetHashCode().ToString()))
                    {
                        result.Msg = Resource.OperationProductProcessing;
                        result.IsSuccess = false;
                        return result;
                    }

                    LogManager.LogHelper.Info(new LogInfo() { Info = "m2" });


                    #endregion

                    #region 3.校验是否合格 STATUS
                    if (!main.STATUS.Equals(EnumGeter.PRODUCTSTAUTS.QUALIFIED.GetHashCode().ToString()))
                    {
                        result.Msg = string.Format("该本体已{1}不能进行{0}!", operationServiceParam.processSet.PROCESSNAME, (main.STATUS.Equals(EnumGeter.PRODUCTSTAUTS.CANCEL.GetHashCode().ToString()) ? "报废" : "返修"));
                        result.IsSuccess = false;
                        return result;
                    }
                    #endregion

                    LogManager.LogHelper.Info(new LogInfo() { Info = "m3" });


                    #region 5.校验当前本体是否加工已经完成 COMPLETEFLAG
                    if (main.COMPLETEFLAG.Equals(EnumGeter.COMPLETEFLAG.COMPLETED.GetHashCode().ToString()))
                    {
                        result.Msg = "该本体已经完成总成装配!";
                        result.IsSuccess = false;
                        return result;
                    }
                    #endregion

                    result.IsSuccess = true;
                    result.BackStatus = true;
                    operationServiceParam.main = main;
                    result.Result = operationServiceParam;

                }


                if (!product.IsMain)//当前零件为零件
                {
                    #region 2.校验出库状态  PROCESSSTATE
                    if (!product.OUTFLAG.Equals(EnumGeter.OUTFLAG.INWAREHOUSE.GetHashCode().ToString()))
                    {
                        DictManageBLL dictProductType = new DictManageBLL(DictKind.PRODUCTTYPE);
                        result.Msg = string.Format("该{0}已出库不能进行{1}!", dictProductType.GetDictValue(product.PRODUCTTYPE), operationServiceParam.processSet.PROCESSNAME);
                        result.IsSuccess = false;
                        return result;
                    }
                    #endregion
                    //判断加工状态
                    List<MainOperation> excuteList = this.GetAllList(new MainOperation { PDID = product.PID });
                    operationServiceParam.moList = excuteList;
                    if (excuteList.Count(o => o.OPERATESTATE == EnumGeter.OPERATESTATE.OPERATING.GetHashCode().ToString()) > 0)
                    {
                        MainOperation priorMo = excuteList.First(o => o.OPERATESTATE == EnumGeter.OPERATESTATE.OPERATING.GetHashCode().ToString());
                        result.Msg = priorMo.PRODUCTCODE + "正在" + priorMo.PROCESSTYPETEXT + "工序进行加工!";
                        result.Msg += "请等待加工完成或是手动放行!";
                        result.IsSuccess = false;
                        return result;
                    }

                    product.processSets = new ProcessSetBLL().GetListByModel(new ProcessSet { PRODUCTTYPE = product.PRODUCTTYPE }).Result;

                    //获取当前工序内容
                    product.processSet = new ProcessSetBLL().GetByModel(new ProcessSet { PRODUCTTYPE = product.PRODUCTTYPE, PROCESSTYPE = product.CURRENTPROCESS }).Result;

                    #region 1.校验零件是否已经被使用 USINGSTATE
                    if (product.USINGSTATE.Equals(EnumGeter.PRODUCTUSESTATE.USED.GetHashCode().ToString()))
                    {
                        DictManageBLL dictProductType = new DictManageBLL(DictKind.PRODUCTTYPE);
                        result.Msg = string.Format("该{0}已使用不能进行{1}!", dictProductType.GetDictValue(product.PRODUCTTYPE), operationServiceParam.processSet.PROCESSNAME);
                        result.IsSuccess = false;
                        return result;
                    }
                    #endregion

                    #region 2.校验零件是否合格 STATUS
                    if (!product.STATUS.Equals(EnumGeter.PRODUCTSTAUTS.QUALIFIED.GetHashCode().ToString()))
                    {
                        DictManageBLL dictProductType = new DictManageBLL(DictKind.PRODUCTTYPE);
                        result.Msg = Resource.OperationProductNotQualified;
                        result.Msg = string.Format("该{0}已{2}不能进行{1}!", dictProductType.GetDictValue(product.PRODUCTTYPE), operationServiceParam.processSet.PROCESSNAME, (product.STATUS.Equals(EnumGeter.PRODUCTSTAUTS.CANCEL.GetHashCode().ToString()) ? "报废" : "返修"));
                        result.IsSuccess = false;
                        return result;
                    }
                    #endregion



                    result.IsSuccess = true;
                    result.BackStatus = false;
                    operationServiceParam.product = product;
                    result.Result = operationServiceParam;
                }
            }
            catch (Exception ex)
            {
                result.IsSuccess = false;
                result.Msg = ex.Message;
                throw;
            }

            return result;
        }



        /// <summary>
        /// 验证先决条件
        /// </summary>
        /// <param name="product"></param>
        /// <returns></returns>
        private DataResult<OperationServiceParam> ValidateProcessRules(Main main, OperationServiceParam operationServiceParam)
        {
            DataResult<OperationServiceParam> result = new DataResult<OperationServiceParam>();
            try
            {
                #region 0.校验零件是否符合当前工序
                //本体应该根据高低配来筛选先决条件
                operationServiceParam.ruleList = operationServiceParam.ruleList.FindAll(m => m.PRODUCTATTR == null || m.PRODUCTATTR == main.HB);

                //当本体当前的工序不等于当前工位的工序时,需要判断该本体的工序到工位之间是否为必须的
                if (!main.CURRENTPROCESS.Equals(operationServiceParam.processSet.PROCESSTYPE))
                {
                    List<ProcessSet> listCompare = main.processSets.FindAll(m => m.PROCESSINDEX >= main.processSet.PROCESSINDEX && m.PROCESSINDEX < operationServiceParam.processSet.PROCESSINDEX);
                    if (listCompare.Count > 0)
                    {
                        foreach (ProcessSet item in listCompare)
                        {
                            if (item.LPNECCESSARY.Equals(EnumGeter.LPNECCESSARY.YES.GetHashCode().ToString()))
                            {
                                //result.Msg = Resource.OperationFitProcess;
                                result.Msg = string.Format("该本体不能进行{0}!\r\n", operationServiceParam.processSet.PROCESSNAME);
                                result.Msg += "应进行" + new ProcessInfoBLL().GetAllList(new ProcessInfo { PROCESSTYPE = item.PROCESSTYPE })[0].PROCESSNAME + "!";
                                result.IsSuccess = false;
                                return result;
                            }
                        }
                    }
                    else
                    {
                        result.Msg = string.Format("该本体不能进行{0}!\r\n", operationServiceParam.processSet.PROCESSNAME);
                        result.Msg += "应进行" + new ProcessInfoBLL().GetAllList(new ProcessInfo { PROCESSTYPE = main.CURRENTPROCESS })[0].PROCESSNAME + "!";
                        result.IsSuccess = false;
                        return result;
                    }
                
                }

                main.CURRENTPROCESS = operationServiceParam.processSet.PROCESSTYPE;
               
                #endregion

                #region 1.获取当前设备对应的先决条中中符合当前零件类别的先决条件集合,如果没有找到对应类别的先决条件,出错  PRODUCTTYPE
                List<ProcessRule> rules = operationServiceParam.ruleList.FindAll(m => m.PRODUCTTYPE == EnumGeter.ProductType.benti.GetHashCode().ToString());
                rules.Sort((a, b) => { return a.RULESORT.CompareTo(b.RULESORT); });
                if (rules.Count <= 0)
                {
                    //result.Msg = Resource.OperationNeedProduct;
                    result.Msg = string.Format(operationServiceParam.processSet.PROCESSNAME + "不需要操作本体!"); ;
                    result.IsSuccess = false;
                    return result;
                }
                #endregion

                #region 2.获取当前零件的加工记录,为了前置工序和冷却时间做准备
                List<MainOperation> operationList = new List<MainOperation>();
                MainOperation operationSearchModel = new MainOperation();
                operationList = operationServiceParam.moList;
                operationList.Sort((m, n) => { return m.CREATEDATE.CompareTo(n.CREATEDATE); });//加工时间倒叙
                #endregion

                #region 3.遍历当前零件类别的先决条件

                foreach (ProcessRule item in rules)
                {

                    #region 3.1 判断当前工序缺少的零件数量
                    if (item.RULETYPE.Equals(EnumGeter.RULETYPE.PARTS.GetHashCode().ToString()))//需求零件
                    {
                        int counts = item.RULEVALUE - item.RULEVALUENOW;//当前需求零件的数量
                        if (counts <= 0)
                        {
                            result.Msg = Resource.OperationLackProduct;
                            result.IsSuccess = false;
                            return result;
                        }
                    }
                    #endregion

                    #region 3.2 判断前置工序
                    else if (item.RULETYPE.Equals(EnumGeter.RULETYPE.BEFOREPROCESS.GetHashCode().ToString()))//前置工序
                    {
                        string beforeProcess = item.RULECONTENT;//前置工序类别  --由于符合了当前工序的匹配那么一定是前置工序是完成的
                        MainOperation operation = operationList.Find(m => m.PROCESSTYPE == beforeProcess);//找到最后一次该工序的加工记录
                        if (operation == null)
                        {
                            result.Msg = Resource.OperationBeforeProcessNotFound;
                            result.IsSuccess = false;
                            return result;
                        }
                        if (operation.OPERATESTATE.Equals(EnumGeter.OPERATIONSTATE.PROCESSING.GetHashCode().ToString()))
                        {
                            result.Msg = Resource.OperationBeforeProcessing;
                            result.IsSuccess = false;
                            return result;
                        }
                    }
                    #endregion

                    #region 3.3 判断冷却时间
                    else if (item.RULETYPE.Equals(EnumGeter.RULETYPE.COOLINGTIME.GetHashCode().ToString()))//冷却时间
                    {
                        int minites = item.RULEVALUE;//需要的冷却时间
                        string beforeProcess = item.RULECONTENT;//冷却工序类别
                        MainOperation operation = operationList.Find(m => m.PROCESSTYPE == beforeProcess);//找到最后一次该工序的加工记录
                        if (operation == null)
                        {
                            result.Msg = Resource.OperationBeforeTimeNotFound;
                            result.IsSuccess = false;
                            return result;
                        }
                        //加工完成时间与当前时间比对
                        DateTime operatedDate = operation.OPERATEDDATE;
                        double comperaValue = (DateTime.Now - operatedDate).TotalMinutes;
                        if (comperaValue < minites)
                        {
                            //result.Msg = string.Format(Resource.OperationBeforeTime, (minites - comperaValue).ToString("f2"));
                            result.Msg = string.Format(item.RULECONTENTTEXT + "工序的" + item.RULETYPETEXT + "还剩{0}分钟!\r\n", (minites - comperaValue).ToString("f2"));
                            result.Msg += string.Format("请达到{0}后再进行{1}!", item.RULETYPETEXT, operationServiceParam.processSet.PROCESSNAME);
                            result.IsSuccess = false;
                            return result;
                        }
                    }
                    #endregion

                    #region 3.4 判断模具
                    else if (item.RULETYPE.Equals(EnumGeter.RULETYPE.COOLINGTIME.GetHashCode().ToString()))//冷却时间
                    {
                        #region  校验3个预制属性
                        if (string.IsNullOrEmpty(operationServiceParam.model.ATTRBUTE1) == false)
                        {
                            string value1 = main.GetType().GetProperty(operationServiceParam.model.ATTRBUTE1).GetValue(main, null).ToString();
                            if (value1.Equals(operationServiceParam.model.VALUE1) == false)
                            {
                                result.Msg = Resource.OperationFitModel;
                                return result;
                            }
                        }
                        if (string.IsNullOrEmpty(operationServiceParam.model.ATTRBUTE2) == false)
                        {
                            string value2 = main.GetType().GetProperty(operationServiceParam.model.ATTRBUTE2).GetValue(main, null).ToString();
                            if (value2.Equals(operationServiceParam.model.VALUE2) == false)
                            {
                                result.Msg = Resource.OperationFitModel;
                                return result;
                            }
                        }
                        if (string.IsNullOrEmpty(operationServiceParam.model.ATTRBUTE3) == false)
                        {
                            string value3 = main.GetType().GetProperty(operationServiceParam.model.ATTRBUTE3).GetValue(main, null).ToString();
                            if (value3.Equals(operationServiceParam.model.VALUE3) == false)
                            {
                                result.Msg = Resource.OperationFitModel;
                                return result;
                            }
                        }
                        #endregion
                    }
                    #region 3.3 判断保质期
                    else if (item.RULETYPE.Equals(EnumGeter.RULETYPE.QUALITYTIME.GetHashCode().ToString()))//保质期
                    {
                        int minites = item.RULEVALUE;//最大保质期间
                        string beforeProcess = item.RULECONTENT;//保质工序类别
                        MainOperation operation = operationList.Find(m => m.PROCESSTYPE == beforeProcess);//找到最后一次该工序的加工记录
                        if (operation == null)
                        {
                            result.Msg = Resource.QualityNotFound;
                            result.IsSuccess = false;
                            return result;
                        }
                        //加工完成时间与当前时间比对
                        DateTime operatedDate = operation.OPERATEDDATE;
                        double comperaValue = (DateTime.Now - operatedDate).TotalMinutes;
                        if (comperaValue > minites)
                        {
                            result.Msg = string.Format(Resource.OperationBehindTime, (minites - comperaValue).ToString("f2"));
                            result.IsSuccess = false;
                            return result;
                        }
                    }
                    #endregion
                    #endregion

                }
                result.IsSuccess = true;
                #endregion
            }
            catch (Exception ex)
            {
                result.IsSuccess = false;
                result.Msg = ex.Message;
                throw;
            }
            return result;
        }




        /// <summary>
        /// 设置本体的先决条件状态
        /// </summary>
        /// <param name="main"></param>
        /// <param name="operationServiceParam"></param>
        /// <returns></returns>
        public DataResult<OperationServiceParam> SetRules(Main main, OperationServiceParam operationServiceParam)
        {
            DataResult<OperationServiceParam> result = new DataResult<OperationServiceParam>();
            try
            {
                #region 4.校验通过,添加入参数,并更新相应先决条件的标识
                //加入到零件列表中
                operationServiceParam.main = main;
                #region 4.1 更新零件数量标识
                //判断先决条件类别
                List<ProcessRule> rules = operationServiceParam.ruleList.FindAll(m => m.PRODUCTTYPE == EnumGeter.ProductType.benti.GetHashCode().ToString());
                ProcessRule itemNum = rules.Find(m => m.RULETYPE == EnumGeter.RULETYPE.PARTS.GetHashCode().ToString());
                if (itemNum.RULETYPE.Equals(EnumGeter.RULETYPE.PARTS.GetHashCode().ToString()))//需求零件
                {
                    int counts = itemNum.RULEVALUE - itemNum.RULEVALUENOW;//当前需求零件的数量
                    //设置先决工序状态
                    itemNum.RULEVALUENOW = 1;//数量
                    if (itemNum.RULEVALUENOW == itemNum.RULEVALUE)//是否满足先决条件
                        SetResult(itemNum, true);
                    else
                        SetResult(itemNum, false);
                }
                #endregion
                //更新先决条件状态
                foreach (ProcessRule item in rules)
                {
                    #region 4.2 更新前置工序的标识  只有自制件才需要前置工序以及冷却时间
                    //只有自制件校验该项
                    if (item.RULETYPE.Equals(EnumGeter.RULETYPE.BEFOREPROCESS.GetHashCode().ToString()))//前置工序
                    {
                        #region 4.2.1 前置工序
                        //判断零件数量是否满足
                        int compareCount = rules.FindAll(m => m.RULETYPE == EnumGeter.RULETYPE.PARTS.GetHashCode().ToString()).Sum(m => m.RULEVALUE - m.RULEVALUENOW);
                        if (compareCount <= 0)//说明零件不缺少
                            SetResult(item, true);
                        else
                            SetResult(item, false);
                        #endregion
                    }
                    else if (item.RULETYPE.Equals(EnumGeter.RULETYPE.COOLINGTIME.GetHashCode().ToString()))//冷却时间
                    {
                        #region 4.2.2 冷却时间

                        //满足前置工序
                        //判断零件数量是否满足
                        int compareCount = rules.FindAll(m => m.RULETYPE == EnumGeter.RULETYPE.PARTS.GetHashCode().ToString()).Sum(m => m.RULEVALUE - m.RULEVALUENOW);
                        if (compareCount <= 0)//说明零件不缺少
                            SetResult(item, true);
                        else
                            SetResult(item, false);
                        #endregion
                    }
                    #endregion
                    #region 3.4 更新模具
                    else if (item.RULETYPE.Equals(EnumGeter.RULETYPE.MODEL.GetHashCode().ToString()))//模具
                    {
                        SetResult(item, true);
                    }
                    #endregion
                    #region 3.4 更新有效期
                    else if (item.RULETYPE.Equals(EnumGeter.RULETYPE.QUALITYTIME.GetHashCode().ToString()))//有效期
                    {
                        #region 4.2.2 有效期

                        //满足前置工序
                        //判断零件数量是否满足
                        int compareCount = rules.FindAll(m => m.RULETYPE == EnumGeter.RULETYPE.PARTS.GetHashCode().ToString()).Sum(m => m.RULEVALUE - m.RULEVALUENOW);
                        if (compareCount <= 0)//说明零件不缺少
                            SetResult(item, true);
                        else
                            SetResult(item, false);
                        #endregion
                    }
                    #endregion
                
                }
                #endregion
                result.IsSuccess = true;
                result.Result = operationServiceParam;
            }
            catch (Exception ex)
            {
                result.IsSuccess = false;
                result.Msg = ex.Message;
                throw;
            }
            return result;

        }

        /// <summary>
        /// 设置零件的先决条件状态
        /// </summary>
        /// <param name="main"></param>
        /// <param name="operationServiceParam"></param>
        /// <returns></returns>
        public DataResult<OperationServiceParam> SetRules(Product product, OperationServiceParam operationServiceParam)
        {
            DataResult<OperationServiceParam> result = new DataResult<OperationServiceParam>();

            try
            {
                //过滤掉相同类型的产品信息
                if (operationServiceParam.productList.Count(o => o.PRODUCTTYPE == product.PRODUCTTYPE) > 0)
                {
                    Product p = operationServiceParam.productList.First(o => o.PRODUCTTYPE == product.PRODUCTTYPE);
                    operationServiceParam.productList.Remove(p);
                }

                //加入到零件列表中
                operationServiceParam.productList.Add(product);

                #region 3.1 更新零件数量
                List<ProcessRule> rules = operationServiceParam.ruleList.FindAll(m => m.PRODUCTTYPE == product.PRODUCTTYPE);
                ProcessRule itemNum = rules.Find(m => m.RULETYPE == EnumGeter.RULETYPE.PARTS.GetHashCode().ToString());

                int countNum = itemNum.RULEVALUE - itemNum.RULEVALUENOW;//当前需求零件的数量
                int proCount = product.CAPACITY - product.USINGCOUNT;//零件剩余数量
                int useCount = 0;//实际使用数量
                if (proCount >= countNum)
                    useCount = countNum;
                else
                    useCount = proCount;
                //需要判断当前零件是否为加工主零件,如果为加工主零件那么不需要扣减数量 ,并且后面为了风道而设置
                if (!product.PRODUCTTYPE.Equals(operationServiceParam.processSet.PRODUCTTYPE) && operationServiceParam.ruleList.Count > 1)
                {
                    product.useCount = useCount;
                    product.USINGCOUNT = product.USINGCOUNT + useCount;//零件的全部使用状态
                    if (product.CAPACITY > product.USINGCOUNT)//设置使用零件的状态
                        product.USINGSTATE = EnumGeter.PRODUCTUSESTATE.USING.GetHashCode().ToString();
                    else
                        product.USINGSTATE = EnumGeter.PRODUCTUSESTATE.USED.GetHashCode().ToString();
                }

                //设置先决工序状态
                itemNum.RULEVALUENOW = itemNum.RULEVALUENOW + useCount;//数量
                if (itemNum.RULEVALUENOW == itemNum.RULEVALUE)//是否满足先决条件
                    SetResult(itemNum, true);
                else
                    SetResult(itemNum, false);

                #endregion

                //更新先决条件状态
                foreach (ProcessRule item in rules)
                {


                    #region 3.2 更新前置工序
                    if (item.RULETYPE.Equals(EnumGeter.RULETYPE.BEFOREPROCESS.GetHashCode().ToString()))//前置工序
                    {

                        //满足前置工序
                        //判断零件数量是否满足
                        int compareCount = rules.FindAll(m => m.RULETYPE == EnumGeter.RULETYPE.PARTS.GetHashCode().ToString()).Sum(m => m.RULEVALUE - m.RULEVALUENOW);
                        if (compareCount <= 0)//说明零件不缺少
                            SetResult(item, true);
                        else
                            SetResult(item, false);
                    }
                    #endregion

                    #region 3.3 更新冷却时间
                    else if (item.RULETYPE.Equals(EnumGeter.RULETYPE.COOLINGTIME.GetHashCode().ToString()))//冷却时间
                    {
                        //满足前置工序
                        //判断零件数量是否满足
                        int compareCount = rules.FindAll(m => m.RULETYPE == EnumGeter.RULETYPE.PARTS.GetHashCode().ToString()).Sum(m => m.RULEVALUE - m.RULEVALUENOW);
                        if (compareCount <= 0)//说明零件不缺少
                            SetResult(item, true);
                        else
                            SetResult(item, false);
                    }
                    #endregion

                    #region 3.4 更新模具
                    else if (item.RULETYPE.Equals(EnumGeter.RULETYPE.MODEL.GetHashCode().ToString()))//模具
                    {
                        if (operationServiceParam.model != null)
                        {
                            SetResult(item, true);
                        }
                        else
                        {
                            SetResult(item, false);
                        }
     
                    }
                    #region 3.4 更新有效期
                    else if (item.RULETYPE.Equals(EnumGeter.RULETYPE.QUALITYTIME.GetHashCode().ToString()))//有效期
                    {
                        #region 4.2.2 有效期

                        //满足前置工序
                        //判断零件数量是否满足
                        int compareCount = rules.FindAll(m => m.RULETYPE == EnumGeter.RULETYPE.PARTS.GetHashCode().ToString()).Sum(m => m.RULEVALUE - m.RULEVALUENOW);
                        if (compareCount <= 0)//说明零件不缺少
                            SetResult(item, true);
                        else
                            SetResult(item, false);
                        #endregion
                    }
                    #endregion
                    #endregion
                }
                #endregion

                result.IsSuccess = true;
                result.Result = operationServiceParam;
            }
            catch (Exception ex)
            {
                result.IsSuccess = false;
                result.Msg = ex.Message;
                throw;
            }

            return result;
        }

        #endregion

        /// <summary>
        /// 验证先决条件
        /// </summary>
        /// <param name="product">零件信息</param>
        /// <param name="operationServiceParam">传递参数</param>
        /// <returns></returns>
        private DataResult ValidateProcessRules(Product product, OperationServiceParam operationServiceParam)
        {
            DataResult result = new DataResult();
            try
            {
                //专门为风道与HUD风道设置
                if (operationServiceParam.main ==null && operationServiceParam.ruleList.Find(m=>m.PRODUCTTYPE ==  EnumGeter.ProductType.benti.GetHashCode().ToString()) == null)
                {
                    operationServiceParam.ruleList = operationServiceParam.ruleList.FindAll(m => m.PRODUCTATTR == null || m.PRODUCTATTR == product.PRODUCTTYPE);
                }
 

                //判断当前零件工序是否为当前工位工序
                if (!product.CURRENTPROCESS.Equals(operationServiceParam.processSet.PROCESSTYPE))
                {
                    //获取当前工位工序在当前零件工序的位置
                    if (product.processSets.Find(m => m.PROCESSTYPE == operationServiceParam.processSet.PROCESSTYPE) == null)
                    {
                        DictManageBLL productType = new DictManageBLL(DictKind.PRODUCTTYPE);
                        result.Msg = string.Format("该{1}不能进行{0}!\r\n", operationServiceParam.processSet.PROCESSNAME, productType.GetDictValue(product.PRODUCTTYPE));
                        result.Msg += "应进行" + new ProcessInfoBLL().GetAllList(new ProcessInfo { PROCESSTYPE = product.CURRENTPROCESS })[0].PROCESSNAME + "!";
                        result.IsSuccess = false;
                        return result;
                    }
                    int processIndes = product.processSets.Find(m => m.PROCESSTYPE == operationServiceParam.processSet.PROCESSTYPE).PROCESSINDEX;
                    List<ProcessSet> listCompare = product.processSets.FindAll(m => m.PROCESSINDEX >= Convert.ToInt32(product.processSet.PROCESSINDEX) && m.PROCESSINDEX < processIndes);
                    if (listCompare.Count > 0)
                    {
                        foreach (ProcessSet item in listCompare)
                        {
                            if (item.LPNECCESSARY.Equals(EnumGeter.LPNECCESSARY.YES.GetHashCode().ToString()))
                            {
                                result.Msg = string.Format("该{1}不能进行{0}!\r\n", operationServiceParam.processSet.PROCESSNAME, item.PRODUCTNAME);
                           
                                result.Msg += "应进行" + new ProcessInfoBLL().GetAllList(new ProcessInfo { PROCESSTYPE = product.CURRENTPROCESS })[0].PROCESSNAME + "!";
                                result.IsSuccess = false;
                                return result;
                            }
                        }
                    }
                    else
                    {
                        DictManageBLL productType = new DictManageBLL(DictKind.PRODUCTTYPE);
                        result.Msg = string.Format("该{1}不能进行{0}!\r\n", operationServiceParam.processSet.PROCESSNAME, productType.GetDictValue(product.PRODUCTTYPE));
                           
                        result.Msg += "应进行" + new ProcessInfoBLL().GetAllList(new ProcessInfo { PROCESSTYPE = product.CURRENTPROCESS })[0].PROCESSNAME + "!";
                        result.IsSuccess = false;
                        return result;
                    }
                }

                product.CURRENTPROCESS = operationServiceParam.processSet.PROCESSTYPE;
                

                #region 3.获取当前设备对应的先决条中中符合当前零件类别的先决条件集合,如果没有找到对应类别的先决条件,出错  PRODUCTTYPE
                List<ProcessRule> rules = operationServiceParam.ruleList.FindAll(m => m.PRODUCTTYPE == product.PRODUCTTYPE);
                rules.Sort((a, b) => { return a.RULESORT.CompareTo(b.RULESORT); });
                if (rules.Count <= 0)
                {
                    result.Msg = Resource.OperationNeedProduct;
                    result.IsSuccess = false;
                    return result;
                }
                #endregion

                #region 4.只有当当前零件为自制件的时候才会获取当前零件的加工记录,为了前置工序和冷却时间做准备
                List<MainOperation> operationList = new List<MainOperation>();
                if (product.productBasic.PRODUCTSOURCE.Equals(EnumGeter.PRODUCTSOURCE.SELFMADE.GetHashCode().ToString()))
                {
                    #region 4.1 获取零件加工记录
                    MainOperation operationSearchModel = new MainOperation();

                    operationList = operationServiceParam.moList;
                    if (operationList.Count > 0)
                    {
                        operationList.Sort((m, n) => { return m.CREATEDATE.CompareTo(n.CREATEDATE); });//加工时间倒叙
                        //判断最后一道工序是否是加工中
                        if (operationList[0].OPERATESTATE.Equals(EnumGeter.OPERATIONSTATE.PROCESSING.GetHashCode().ToString()))
                        {
                            result.Msg = Resource.OperationProductProcessing;
                            result.IsSuccess = false;
                            return result;
                        }
                    }

                    #endregion

                    #region 4.2 遍历规则校验
                    foreach (ProcessRule item in rules)
                    {
                        #region 4.2.1 校验数量
                        if (item.RULETYPE.Equals(EnumGeter.RULETYPE.PARTS.GetHashCode().ToString()))//需求零件
                        {
                            int counts = item.RULEVALUE - item.RULEVALUENOW;//当前需求零件的数量
                            if (counts <= 0)
                            {
                                result.Msg = Resource.OperationLackProduct;
                                result.IsSuccess = false;
                                return result;
                            }
                        }
                        #endregion

                        #region 4.2.2 校验前置工序
                        else if (item.RULETYPE.Equals(EnumGeter.RULETYPE.BEFOREPROCESS.GetHashCode().ToString()))//前置工序
                        {
                            string beforeProcess = item.RULECONTENT;//前置工序类别  --由于符合了当前工序的匹配那么一定是前置工序是完成的
                            MainOperation operation = operationList.Find(m => m.PROCESSTYPE == beforeProcess);//找到最后一次该工序的加工记录
                            if (operation == null)
                            {
                                result.Msg = Resource.OperationBeforeProcessNotFound;
                                result.IsSuccess = false;
                                return result;
                            }
                            if (operation.OPERATESTATE.Equals(EnumGeter.OPERATIONSTATE.PROCESSING))
                            {
                                result.Msg = Resource.OperationBeforeProcessing;
                                result.IsSuccess = false;
                                return result;
                            }
                        }
                        #endregion

                        #region 4.2.3 校验冷却时间
                        else if (item.RULETYPE.Equals(EnumGeter.RULETYPE.COOLINGTIME.GetHashCode().ToString()))//冷却时间
                        {
                            int minites = item.RULEVALUE;//需要的冷却时间
                            string beforeProcess = item.RULECONTENT;//冷却工序类别
                            MainOperation operation = operationList.Find(m => m.PROCESSTYPE == beforeProcess);//找到最后一次该工序的加工记录
                            if (operation == null)
                            {
                                result.Msg = Resource.OperationBeforeTimeNotFound;
                                result.IsSuccess = false;
                                return result;
                            }
                            //加工完成时间与当前时间比对
                            DateTime operatedDate = operation.OPERATEDDATE;
                            double comperaValue = (DateTime.Now - operatedDate).TotalMinutes;
                            if (comperaValue < minites)
                            {
                                //result.Msg = string.Format(Resource.OperationBeforeTime, (minites - comperaValue).ToString("f2"));
                                DictManageBLL dictProductType = new DictManageBLL(DictKind.PRODUCTTYPE);
                                result.Msg = string.Format(dictProductType.GetDictValue(product.PRODUCTTYPE) + "在" + item.RULECONTENTTEXT + "工序的" + item.RULETYPETEXT + "还剩{0}分钟!\r\n", (minites - comperaValue).ToString("f2"));
                                result.Msg += string.Format("请达到{0}后再进行{1}!", item.RULETYPETEXT, operationServiceParam.processSet.PROCESSNAME);
                                result.IsSuccess = false;
                                return result;
                            }
                        }
                        #endregion

                        #region 4.2.4 校验模具
                        if (item.RULETYPE.Equals(EnumGeter.RULETYPE.MODEL.GetHashCode().ToString()))//模具
                        {
                            if (product != null && operationServiceParam.model != null)
                            {
                                #region  校验3个预制属性
                                if (string.IsNullOrEmpty(operationServiceParam.model.ATTRBUTE1) == false)
                                {
                                    string value1 = product.GetType().GetProperty(operationServiceParam.model.ATTRBUTE1).GetValue(product, null).ToString();
                                    if (value1.Equals(operationServiceParam.model.VALUE1) == false)
                                    {
                                        result.Msg = Resource.OperationFitModel;
                                        return result;
                                    }
                                }
                                if (string.IsNullOrEmpty(operationServiceParam.model.ATTRBUTE2) == false)
                                {
                                    string value2 = product.GetType().GetProperty(operationServiceParam.model.ATTRBUTE2).GetValue(product, null).ToString();
                                    if (value2.Equals(operationServiceParam.model.VALUE2) == false)
                                    {
                                        result.Msg = Resource.OperationFitModel;
                                        return result;
                                    }
                                }
                                if (string.IsNullOrEmpty(operationServiceParam.model.ATTRBUTE3) == false)
                                {
                                    string value3 = product.GetType().GetProperty(operationServiceParam.model.ATTRBUTE3).GetValue(product, null).ToString();
                                    if (value3.Equals(operationServiceParam.model.VALUE3) == false)
                                    {
                                        result.Msg = Resource.OperationFitModel;
                                        return result;
                                    }
                                }
                                #endregion
                            }
                        }

#endregion

                        #region 3.3 判断保质期
                        if (item.RULETYPE.Equals(EnumGeter.RULETYPE.QUALITYTIME.GetHashCode().ToString()))//保质期
                        {
                            DictManageBLL dictProductType = new DictManageBLL(DictKind.PRODUCTTYPE);
                            DictManageBLL dictProcessType = new DictManageBLL(DictKind.PROCESSTYPE);
                            
                            int minites = item.RULEVALUE;//最大保质期间
                            string beforeProcess = item.RULECONTENT;//保质工序类别
                            MainOperation operation = operationList.Find(m => m.PROCESSTYPE == beforeProcess);//找到最后一次该工序的加工记录
                            if (operation == null)
                            {
                                result.Msg = Resource.QualityNotFound;
                                result.IsSuccess = false;
                                return result;
                            }
                            //加工完成时间与当前时间比对
                            DateTime operatedDate = operation.OPERATEDDATE;
                            double comperaValue = (DateTime.Now - operatedDate).TotalMinutes;
                            if (comperaValue > minites)
                            {
                                result.Msg = dictProductType.GetDictValue(product.PRODUCTTYPE) + product.PRODUCTCODE + "已经超出" + dictProcessType.GetDictValue(beforeProcess) + "工序的保质期!\r\n不能继续使用!";
                                result.IsSuccess = false;
                                return result;

                            }
                        }
                        #endregion
                    }
                    #endregion

                }
                #endregion

                result.IsSuccess = true;
            }
            catch (Exception ex)
            {
                result.IsSuccess = false;
                result.Msg = ex.Message;
                throw;
            }

            return result;
        }

        /// <summary>
        /// 设置通过
        /// </summary>
        /// <param name="item">当前规则</param>
        /// <param name="result">规则结果</param>
        /// <returns></returns>
        public void SetResult(ProcessRule item, bool result)
        {
            //设置是否ok
            item.isValid = true;
            item.isOk = result;
            if (result)
            {
                item.isOkTEXT = Resource.OperationPass;
            }
            else
            {
                item.isOkTEXT = Resource.OperationUnpass;
            }
        }


        /// <summary>
        /// 校验是否全部通过
        /// </summary>
        /// <param name="operationServiceParam">传递参数</param>
        /// <returns></returns>
        public bool ValidateResult(OperationServiceParam operationServiceParam)
        {
            //判断所有先决是否全ok
            foreach (ProcessRule item in operationServiceParam.ruleList)
            {
                if (item.isOk == false)
                {
                    return false;
                }
            }
            return true;
        }


        /// <summary>
        /// 调取保存,并发送指令
        /// </summary>
        /// <param name="operationServiceParam">传递参数</param>
        /// <returns></returns>
        public DataResult SaveAndSendOrder(OperationServiceParam operationServiceParam)
        {

            DataResult result = new DataResult();
            try
            {
                //填充数据
                result = GetParamModels(operationServiceParam);

                if (result.IsSuccess)
                {
                    DataResult<int> resultInt = this.MachineOperation(operationServiceParam);//更新零件状态
                    if (resultInt.IsSuccess)
                    {
                        result.IsSuccess = true;
                        result.Msg = Resource.OperationSendSuccess;
                        if (operationServiceParam.machineInfo.ISCONTROL.Equals("0"))//如果不需要返回参数的那么直接后台放行,读取设备的标示operationServiceParam.machineInfo.ISCONTROL
                        {
                            string pcode = operationServiceParam.main == null? operationServiceParam.productList[0].PRODUCTCODE:operationServiceParam.main.EPIDERMISCODE;
                            string productid = "";
                            if (operationServiceParam.main == null)
                            {
                                productid = operationServiceParam.productList[0].PID;
                            }

                            SetPassProcessToNext(new Product { PRODUCTCODE = pcode, PID = productid });

                            result.Msg = "加工完成!";
                        }
                    }
                    else
                    {
                        result.Msg = resultInt.Msg;
                        result.IsSuccess = false;
                    }
                }
            }
            catch (Exception ex)
            {
                LogManager.LogHelper.Error(new LogInfo()
                {
                    ErrorInfo = ex,
                    Tag = ex.StackTrace,
                    Info = "加工操作保存发送-插入信息"
                });
                result.IsSuccess = false;
                result.Msg = Resource.SystemException;
                throw;
            }

            return result;
        }


        /// <summary>
        /// 加工操作全流程
        /// </summary>
        /// <param name="productCode"></param>
        /// <param name="operationServiceParam"></param>
        /// <returns></returns>
        public DataResult<OperationServiceParam> OperationForReturn(string productCode, OperationServiceParam operationServiceParam)
        {
            DataResult<OperationServiceParam> resultFinal = new DataResult<OperationServiceParam>();
            resultFinal = this.Operation( productCode,  operationServiceParam);
            //获取指令方法
            Process.ProcessOrderSend proOrderSend = new Process.ProcessOrderSend();
            MachineInfo mInfo = operationServiceParam.machineInfo;
            mInfo.MOLDNUMBER = operationServiceParam.machineInfo.MOLDNUMBER.Trim();
            ///////////////
            //mInfo.MOLDNUMBER = "1";
            //List<ParameterConfig> listParam1 = proOrderSend.Get(mInfo, true);
            //if (listParam1.Count > 0)
            //{
            //    string jstring1 = QMFrameWork.Common.Serialization.JsonConvertHelper.GetSerializes(listParam1);
            //    resultFinal.MsgCode = jstring1;
            //    return resultFinal;
            //}
            ////////////////
            
            
            return resultFinal;
        }

        /// <summary>
        /// 获取指令参数
        /// </summary>
        /// <param name="mInfo"></param>
        /// <param name="orderFlag"></param>
        /// <returns></returns>
        public DataResult<string> GetSendOrder(MachineInfo mInfo, bool orderFlag)
        {
            DataResult<string> str = new DataResult<string>();
            Process.ProcessOrderSend proOrderSend = new Process.ProcessOrderSend();

            List<ParameterConfig> listParam = proOrderSend.Get(mInfo, orderFlag);
            if (listParam.Count > 0)
            {
                string jstring = QMFrameWork.Common.Serialization.JsonConvertHelper.GetSerializes(listParam);
                str.Result = jstring;
            }
            return str;
        }

        /// <summary>
        /// 加工操作全流程
        /// </summary>
        /// <param name="productCode"></param>
        /// <param name="operationServiceParam"></param>
        /// <returns></returns>
        public DataResult<OperationServiceParam> Operation(string productCode, OperationServiceParam operationServiceParam)
        {
            DataResult<OperationServiceParam> resultFinal = new DataResult<OperationServiceParam>();
            DataResult result = new DataResult();
            try
            {
            
                resultFinal.IsSuccess = true;
                resultFinal.Result = operationServiceParam;
                resultFinal.Result.isPass = false;

                //添加线程锁
                using (MutexLock stockLock = new MutexLock(operationServiceParam.machineInfo.MACHINECODDE + ":Check"))
                {

                   

                    #region 0.判断当前设备加工状态

                    DataResult resultMachine = this.GetMashineStatus(operationServiceParam);
                    if (resultMachine.IsSuccess == false)//零件处理失败
                    {
                        //设备正在加工中需要判断是否暂停,需要继续加工,并重新发送指令
                        if (resultMachine.Msg.Equals(Resource.OperationMachineWorking))
                        {
                            //并且符合零件组合
                            //需要判断是否全部符合当前工序
                            //并且全都是加工中的状态

                        }
                        resultFinal.Msg = resultMachine.Msg;
                        return resultFinal;
                    }
                    #endregion

                 

                    #region 1.判断条码类别

                    if (productCode.Length < 3)//为模具条码
                    {
                        #region
                        operationServiceParam.model = new MachineInfoModels();
                        operationServiceParam.model.MODELCODE = productCode;
                        operationServiceParam.model.MODELSTATION = productCode;
                        operationServiceParam.machineInfo.MOLDNUMBER = productCode;
                        DataResult modelResult = this.ValidateModel(operationServiceParam);
                        if (modelResult.IsSuccess == false)
                        {
                            resultFinal.Msg = modelResult.Msg;
                            return resultFinal;
                        }
                        #endregion
                    }
                    if (productCode.Length > 3)//为零件条码
                    {

                        #region 判断与服务器交互的设备是否加工完成

                        //2016-6-27 闫永刚 获取模架号加工状态信息
                        //如果该模架正在加工中,那么不能进行操作,
                        if (operationServiceParam.machineInfo.ISCONTROL == "3"
                            && operationServiceParam.machineInfo.PROCESSTYPE != EnumGeter.ProcessType.jiaozhu.GetHashCode().ToString())
                        {

                            #region 模架使用校验

                            MainMolderStatus entity = new MainMolderStatusDAL().Get(
                                new MainMolderStatus()
                                {
                                    MACHINECODDE = operationServiceParam.machineInfo.MACHINECODDE,
                                    MOLDNUMBER = "1"
                                }
                                );

                            if (entity.OPERATIONFLAG.ToString() == EnumGeter.OPERATIONFLAG.BUSY.GetHashCode().ToString()
                                && entity.BARCODE.Trim().ToUpper().Contains(productCode.Trim().ToUpper()) == false)
                            {

                                //闫永刚2016-10-18  因为冲切设备总是不反回加工结果,所以这里重新调整
                                //当冲切设备在使用中做额外处理
                                //if (operationServiceParam.machineInfo.PROCESSTYPE != EnumGeter.ProcessType.chongqie.GetHashCode().ToString())
                                //{
                                //    resultFinal.Msg = string.Format("设备正在加工中,请等待加工完成或是手动放行!");
                                //    return resultFinal;
                                //}
                                //else
                                //{

                                //    DataResult res = SetPunchingPassProcess();
                                //    if (res.IsSuccess == false)
                                //    {
                                //        resultFinal.Msg = string.Format("Releas Punch exception!");
                                //        return resultFinal;
                                //    }
                                //}

                                resultFinal.Msg = string.Format("设备正在加工中,请等待加工完成或是手动放行!");
                                return resultFinal;
                            }

                            #endregion
                           
                        }

                        #endregion

                        #region 1.处理零件信息,添加外购件,设置零件类别

                        DataResult<Product> resultProduct = this.ExplainProduct(productCode, operationServiceParam);
                        if (resultProduct.IsSuccess == false)//零件处理失败
                        {
                            resultFinal.Msg = resultProduct.Msg;
                            return resultFinal;
                        }
                        #endregion

                    

                        #region 2.零件的属性校验,是否合格

                        DataResult<OperationServiceParam> dataResultObject = this.ValidateProudct(resultProduct.Result, operationServiceParam);
                        operationServiceParam = dataResultObject.Result as OperationServiceParam;
                        if (dataResultObject.IsSuccess == false)//零件校验不通过
                        {
                            resultFinal.Msg = dataResultObject.Msg;
                            return resultFinal;
                        }
                        #endregion

                      

                        #region 3.校验零件是否符合加工先决条件
                        if (dataResultObject.BackStatus)//为本体
                        {
                            Main main = operationServiceParam.main;

                            #region 本体
                            //校验先决条件
                            DataResult<OperationServiceParam> dataResultRule = this.ValidateProcessRules(main, operationServiceParam);
                            if (dataResultRule.IsSuccess == false)
                            {
                                if (dataResultRule.Result != null)
                                    operationServiceParam.ruleList = dataResultRule.Result.ruleList;
                                resultFinal.Msg = dataResultRule.Msg;
                                return resultFinal;
                            }

                            //更新先决条件列表
                            DataResult<OperationServiceParam> resultRules = this.SetRules(main, operationServiceParam);
                            if (resultRules.IsSuccess == false)
                            {
                                resultFinal.Msg = resultRules.Msg;
                                return resultFinal;
                            }

                            #endregion

                            operationServiceParam = resultRules.Result;
                        }
                        else//为零件
                        {
                            Product product = operationServiceParam.product;
                            //校验先决条件

                            #region 零件

                            result = this.ValidateProcessRules(product, operationServiceParam);
                            if (result.IsSuccess == false)
                            {
                                resultFinal.Msg = result.Msg;
                                return resultFinal;
                            }
                            //更新先决条件列表
                            DataResult<OperationServiceParam> resultRules = this.SetRules(product, operationServiceParam);
                            if (resultRules.IsSuccess == false)
                            {
                                resultFinal.Msg = resultRules.Msg;
                                return resultFinal;
                            }

                            #endregion

                            operationServiceParam = resultRules.Result;
                        }
                        resultFinal.Result = operationServiceParam;//更新完先决条件就加入返回值中
                        #endregion

                        
                    }

                    #endregion

                    #region 处理批量件
                    //
                    //判断当前工序是否存在批量件
                    List<ProcessRule> listRule = operationServiceParam.ruleList.FindAll
                        (m => m.PRODUCTUNIT.Equals(EnumGeter.PRODUCTUNIT.SET.GetHashCode().ToString())
                        && m.RULEVALUE > m.RULEVALUENOW);
                    if (listRule != null && listRule.Count > 0)
                    {
                        foreach (ProcessRule item in listRule)
                        {
                            ProductBLL pBll = new ProductBLL();
                            List<Product> listP = pBll.GetAllList(new Product { PRODUCTTYPE = item.PRODUCTTYPE, USINGSTATE = EnumGeter.PRODUCTUSESTATE.USING.GetHashCode().ToString() });
                            listP.Sort((m, n) => n.UPDATEDATE.CompareTo(m.UPDATEDATE));
                            //如果为总成装配工序需要判断外购件颜色(格栅需要判断颜色)
                            if (operationServiceParam.processSet.PROCESSTYPE.Equals(EnumGeter.ProcessType.zongchengzhuangpei.GetHashCode().ToString())
                                && (item.PRODUCTTYPE.Equals(EnumGeter.ProductType.geshan.GetHashCode().ToString()) || item.PRODUCTTYPE.Equals(EnumGeter.ProductType.yougeshan.GetHashCode().ToString())))
                            {
                                DictManageBLL dictCOLORTOGESHANBll = new DictManageBLL(DictKind.COLORTOGESHAN);
                                DictManageBLL dictCOLORBll = new DictManageBLL(DictKind.COLOR);

                                if (operationServiceParam.main == null)
                                {
                                    resultFinal.Msg = "请先扫描本体条码!";
                                    return resultFinal;
                                }

                                string maincolorText = dictCOLORBll.GetDictValue(operationServiceParam.main.COLOR);

                                string colorText = "";
                                foreach (Product p in listP)
                                {

                                    LogManager.LogHelper.Info(new LogInfo() { Info = "---------" + p.PRODUCTCODE + " / " + productCode });

                                    if (p.PRODUCTCODE.Length != 18)
                                    {
                                        resultFinal.Msg = item.PRODUCTTYPETEXT + "条码" + p.PRODUCTCODE + "格式错误,请扫码准确的" + item.PRODUCTTYPETEXT + "条码!";
                                        return resultFinal;
                                    }
                                    string color = p.PRODUCTCODE.Substring(12, 3);
                                    //颜色代码——“24A”代表注塑黑色,“6PS”代表喷漆黑色,“RK1”代表灰色,“AY2”代表棕色
                                    string mainColor = dictCOLORTOGESHANBll.GetDictValue(color);
                                    colorText = dictCOLORBll.GetDictValue(mainColor);
                                    if (string.IsNullOrEmpty(colorText))
                                    {
                                        resultFinal.Msg = p.PRODUCTCODE + "颜色码不正确!";
                                        return resultFinal;
                                    }
                                    if (operationServiceParam.main == null)
                                    {
                                        resultFinal.Msg = "继续扫描本体码!";
                                        return resultFinal;
                                    }


                                    LogManager.LogHelper.Info(new LogInfo() { Info = "mainColor:" + mainColor.ToString() + " / " + "operationServiceParam.main.COLOR:" + operationServiceParam.main.COLOR.ToString()});
                                    
                                    if (mainColor.Equals(operationServiceParam.main.COLOR))
                                    {
                                        LogManager.LogHelper.Info(new LogInfo() { Info = "SetRules" });
                                    
                                        //设置零件状态
                                        SetRules(p, operationServiceParam);
                                    }
                                    if (item.RULEVALUE <= item.RULEVALUENOW) { break; }
                                }
                                if (item.RULEVALUE > item.RULEVALUENOW)
                                {
                                    LogManager.LogHelper.Info(new LogInfo() { Info = "RULEVALUE:" + item.RULEVALUE.ToString() + " / " + "RULEVALUENOW:" + item.RULEVALUENOW.ToString()});
                                    
                                    Dictionary<string, string> dict = new DictManageBLL(DictKind.COLORTOGESHAN).GetModelDictionary(DictKind.COLORTOGESHAN);
                                    string colorinfo = "";
                                    foreach (var v in dict)
                                    {
                                        if (v.Value == operationServiceParam.main.COLOR)
                                        {
                                            colorinfo += v.Key;
                                            colorinfo += ",";
                                        }

                                    }
                                    colorinfo = colorinfo.Substring(0, colorinfo.Length - 1);
                                    resultFinal.Msg = "缺少" + item.PRODUCTTYPETEXT + Environment.NewLine + "请扫描以" + (item.PRODUCTTYPE == EnumGeter.ProductType.geshan.GetHashCode().ToString() ? "B9H" : "B9I") + string.Format("开头并且条码中包含{0}的", colorinfo) + maincolorText + "色" + item.PRODUCTTYPETEXT + "条码!";
                                    return resultFinal;
                                }
                            }
                            else
                            {
                                if (operationServiceParam.main == null)
                                {
                                    resultFinal.Msg = "继续扫描本体码!";
                                    return resultFinal;
                                }
                                foreach (Product p in listP)
                                {
                                    //设置零件状态
                                    SetRules(p, operationServiceParam);
                                    if (item.RULEVALUE <= item.RULEVALUENOW) { break; }
                                }
                                if (item.RULEVALUE > item.RULEVALUENOW)
                                {
                                    resultFinal.Msg = "缺少" + item.PRODUCTTYPETEXT + ",请添加并取消操作重新扫码!";
                                    return resultFinal;
                                }
                            }

                        }
                    }

                    #endregion

                    #region 4.判断加工先决条件是否全部通过

                    if (this.ValidateResult(operationServiceParam) == false)
                    {
                        resultFinal.Msg = "";
                        return resultFinal;
                    }

                    #endregion

                    //判断是否该零件存在于先决条件中,否则删除该零件
                    for (int i = 0; i < operationServiceParam.productList.Count; i++)
                    {
                        Product item = operationServiceParam.productList[i];
                        if (operationServiceParam.ruleList.Find(m => m.RULETYPE.Equals("2") && m.PRODUCTTYPE.Equals(item.PRODUCTTYPE)) == null)
                        {
                            operationServiceParam.productList.Remove(item);
                            i--;
                        }
                    }


                    #region 5.更新加工零件状态并发送设备指令



                    result = this.SaveAndSendOrder(operationServiceParam);

                    if (result.IsSuccess == false)
                    {
                        resultFinal.Msg = result.Msg;
                        return resultFinal;
                    }
                    #endregion

                }

                resultFinal.Result.isPass = true;
                resultFinal.Msg = Resource.OperationSendSuccess;
            }
            catch (Exception ex)
            {
                LogManager.LogHelper.Error(new LogInfo()
                {
                    ErrorInfo = ex,
                    Tag = ex.StackTrace,
                    Info = "加工操作-流程加工"
                });
                result.IsSuccess = false;
                resultFinal.Msg = Resource.SystemException;
            }

            return resultFinal;
        }

        public DataResult<Main> GetPrintCode(Product product)
        {


            DataResult<Main> result = new DataResult<Main>();
            Main main = new Main();

            //string mainCode = new MainDAL().GetMaxMainCode();
            //20190402屏蔽
            string mainCode = "屏蔽";
            if (string.IsNullOrEmpty(mainCode))
            {
                mainCode = "1";
            }
            else
            {
                mainCode = (Convert.ToInt32(mainCode) + 1) + "";
            }
            main.MAINCODE = "052 M3G" + mainCode.PadLeft(7, '0');
            main.MAINCODE = new FileCopyRecordDAL().GetBarcode(main.MAINCODE);
            main.COMPLETETIME = DateTime.Now;

            PrintCode pc = new PrintCode();
            pc.PID = Guid.NewGuid().ToString();
            pc.PRODUCTCODE = product.PRODUCTCODE;
            pc.MAINCODE = main.MAINCODE;
            pc.ISCOMPLETE = 0;
            pc.CREATETIME = System.DateTime.Now;

            PrintCodeDAL dal = new PrintCodeDAL();
            dal.Insert(pc);
            result.Result = main;
            return result;
        }


        /// <summary>
        /// 成都注塑条码打印
        /// </summary>
        /// <param name="product"></param>
        /// <returns></returns>
        public DataResult<List<PrintCode>> GetPrintCodeForChengdu(List<Material> materialList,MachineInfoModels model, int proNum)
        {
            DataResult<List<PrintCode>> result = new DataResult<List<PrintCode>>();
            List<PrintCode> printCodeList = new List<PrintCode>();
            PrintCodeDAL dal = new PrintCodeDAL();
            foreach (Material item in materialList)
            {
                PrintCode proCodeInfo = new PrintCode();
                proCodeInfo.PRODUCTCODE = item.MATERIAL_CODE;
                //获取PrinCode信息
                for (int i = 0; i < proNum; i++)
                {
                    proCodeInfo = new PrintCodeDAL().GetPrintCodeInfo(proCodeInfo);
                    if (proCodeInfo != null)
                    {
                        if (proCodeInfo.UPDATETIME.ToShortDateString() != DateTime.Now.ToShortDateString())
                        {
                            proCodeInfo.SERIAL_NUM = 0;
                            dal.UpdateBySql(proCodeInfo);
                        }
                        string modelcode = "0";
                        if (model != null && !string.IsNullOrEmpty(model.PID))
                        {
                            modelcode = model.MODELSTATION;
                        }

                        string time = DateTime.Now.ToString("yyMMddHHmm");
                        proCodeInfo.SERIAL_NUM = proCodeInfo.SERIAL_NUM + 1;
                        string serialnumber = (proCodeInfo.SERIAL_NUM).ToString().PadLeft(4, '0');
                        proCodeInfo.MAINCODE = proCodeInfo.PRECODE + modelcode + time + serialnumber;
                        dal.Update(proCodeInfo);
                        printCodeList.Add(proCodeInfo);
                    }
                }
            }
            result.Result = printCodeList;
            return result;
        }

        /// <summary>
        /// 成都注塑条码打印带注塑参数
        /// </summary>
        /// <param name="product"></param>
        /// <returns></returns>
        public DataResult<List<PrintCode>> GetPrintCodeWithParam(List<Material> materialList,MachineInfo machine,MachineInfoModels model,string tableName,Dictionary<string,string> param)
        {
            DataResult<List<PrintCode>> result = new DataResult<List<PrintCode>>();
            List<PrintCode> printCodeList = new List<PrintCode>();
            List<MainOperation> molist = new List<MainOperation>();
            List<string> paramsqls = new List<string>();
            PrintCodeDAL dal = new PrintCodeDAL();
            StringBuilder sql = new StringBuilder();

            foreach (Material item in materialList)
            {
                PrintCode proCodeInfo = new PrintCode();
                proCodeInfo.PRODUCTCODE = item.MATERIAL_CODE;
                proCodeInfo = new PrintCodeDAL().GetPrintCodeInfo(proCodeInfo);
                if (proCodeInfo != null)
                {
                    if (proCodeInfo.UPDATETIME.ToShortDateString() != DateTime.Now.ToShortDateString())
                    {
                        proCodeInfo.SERIAL_NUM = 0;
                        dal.UpdateBySql(proCodeInfo);
                    }
                    string modelcode="0";
                    if (model != null&&!string.IsNullOrEmpty(model.PID))
                    {
                        modelcode = model.MODELSTATION;
                    }

                    string time = DateTime.Now.ToString("yyMMddHHmm");
                    proCodeInfo.SERIAL_NUM = proCodeInfo.SERIAL_NUM + 1;
                    string serialnumber = (proCodeInfo.SERIAL_NUM).ToString().PadLeft(4, '0');
                    proCodeInfo.MAINCODE = proCodeInfo.PRECODE + modelcode + time + serialnumber;
                    dal.Update(proCodeInfo);
                    printCodeList.Add(proCodeInfo);
                    string pid=Guid.NewGuid().ToString();
                    MainOperation mo = new MainOperation
                    {
                        PID = pid,
                        PDID = pid,
                        PRODUCTCODE = proCodeInfo.MAINCODE,
                        MACHINENAME = machine.MACHINENAME,
                        MACHINECODDE = machine.MACHINECODDE,
                        MOLDNUMBER = model.MODELCODE,
                        STATUS = "0",
                        OPERATESTATE = string.IsNullOrEmpty(tableName)?"2":"1",//如果不包含参数信息则认为是手动打印
                        OPERATEDDATE = DateTime.Now,
                        MODELSTATION = model.MODELSTATION,
                        CREATEUSER = base.LoginUser.UserID,
                        CREATEDATE = DateTime.Now,
                        UPDATEDATE = DateTime.Now,
                        MATERIAL_CODE = item.MATERIAL_CODE,
                        MATERIAL_TYPE_CODE = item.MATERIAL_TYPE_CODE,
                        WORKCENTER_CODE = machine.WORKCENTER_CODE,
                        WORKCELL_CODE = machine.WORKCELL_CODE
                    };
                    molist.Add(mo);
                    if (!string.IsNullOrEmpty(tableName))
                    {
                        StringBuilder columns = new StringBuilder();
                        StringBuilder values = new StringBuilder();
                        columns.Append("[PID],[PDID],[PRODUCTCODE],[MOID],[MACHINENAME],[MACHINECODDE],[MOLDNUMBER],[CREATEDATE],[OPERATEDATE]");
                        values.Append(string.Format("'{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}'"
                            , pid, pid, mo.PRODUCTCODE, mo.PID, mo.MACHINENAME, mo.MACHINECODDE, mo.MOLDNUMBER, mo.CREATEDATE, mo.OPERATEDDATE));

                        foreach (var pa in param)
                        {
                            columns.Append(string.Format(",[{0}]", pa.Key));
                            values.Append(string.Format(",'{0}'", pa.Value));
                        }
                        sql.AppendLine(string.Format("INSERT INTO [{0}]({1}) VALUES({2}) "
                            , tableName
                            , columns.ToString()
                            , values.ToString()));
                    }
                }
            }
            using (var session = AppDataFactory.CreateMainSession())
            {
                session.Insert(molist);
                if (sql.Length > 0)
                {
                    session.ExecuteSql(sql.ToString());
                }
            }
            result.Result = printCodeList;
            return result;
        }

        /// <summary>
        /// 加工操作全流程
        /// </summary>
        /// <param name="productCode"></param>
        /// <param name="operationServiceParam"></param>
        /// <returns></returns>
        public DataResult<OperationServiceParam> OperationList(List<string> productCodes, OperationServiceParam operationServiceParam)
        {
            DataResult<OperationServiceParam> resultFinal = new DataResult<OperationServiceParam>();
            DataResult result = new DataResult();
            try
            {
                string productCode = "";
                for (int i = 0; i < productCodes.Count; i++)
                {
                    productCode = productCodes[i];

                    resultFinal.IsSuccess = true;
                    resultFinal.Result = operationServiceParam;


                    #region 0.判断当前设备加工状态
                    if (i == 0)//当参数为列表时候只有第一个参数需要校验设备状态
                    {
                        DataResult resultMachine = this.GetMashineStatus(operationServiceParam);
                        if (resultMachine.IsSuccess == false)//零件处理失败
                        {
                            //设备正在加工中需要判断是否暂停,需要继续加工,并重新发送指令
                            if (resultMachine.Msg.Equals(Resource.OperationMachineWorking))
                            {
                                //并且符合零件组合
                                //需要判断是否全部符合当前工序
                                //并且全都是加工中的状态
                                foreach (string pCode in productCodes)
                                {
                                    Main mian = new MainDAL().GetMain(new Main { publicCode = productCode });
                                    //当本体存在并且工序为当前工序,并且状态为正在加工中,那么只需要重新发送指令
                                    if (mian != null && mian.CURRENTPROCESS.Equals(operationServiceParam.processSet.PROCESSTYPE) && mian.PROCESSSTATE.Equals(EnumGeter.OPERATESTATE.COMPLETED.GetHashCode().ToString()))
                                    {
                                        resultFinal.IsSuccess = true;
                                        resultFinal.Result.isPass = true;
                                        resultFinal.Msg = Resource.OperationSendSuccess;
                                        return resultFinal;
                                    }
                                }
                            }
                            resultFinal.Msg = resultMachine.Msg;
                            return resultFinal;
                        }
                    }
                    #endregion

                    #region 1.判断条码类别
                    if (productCode.Length < 3)//为模具条码
                    {
                        #region
                        operationServiceParam.model = new MachineInfoModels();
                        operationServiceParam.model.MODELCODE = productCode;
                        DataResult modelResult = this.ValidateModel(operationServiceParam);
                        if (modelResult.IsSuccess == false)
                        {
                            resultFinal.Msg = modelResult.Msg;
                            return resultFinal;
                        }
                        #endregion
                    }
                    if (productCode.Length > 3)//为零件条码
                    {
                        #region 1.处理零件信息,添加外购件,设置零件类别
                        DataResult<Product> resultProduct = this.ExplainProduct(productCode, operationServiceParam);
                        if (resultProduct.IsSuccess == false)//零件处理失败
                        {
                            resultFinal.Msg = resultProduct.Msg;
                            return resultFinal;
                        }
                        #endregion



                        //OperationServiceParam operationServiceParam
                        #region 2.零件的属性校验,是否合格
                        DataResult<OperationServiceParam> dataResultObject = this.ValidateProudct(resultProduct.Result, operationServiceParam);
                        operationServiceParam = dataResultObject.Result as OperationServiceParam;
                        
                        if (dataResultObject.IsSuccess == false)//零件校验不通过
                        {
                            resultFinal.Msg = dataResultObject.Msg;
                            return resultFinal;
                        }
                        #endregion

                        #region 3.校验零件是否符合加工先决条件
                        if (dataResultObject.BackStatus)//为本体
                        {
                            Main main = operationServiceParam.main;

                            //校验先决条件
                            DataResult<OperationServiceParam> dataResultRule = this.ValidateProcessRules(main, operationServiceParam);
                            if (dataResultRule.IsSuccess == false)
                            {
                                if (dataResultRule.Result != null)
                                    operationServiceParam.ruleList = dataResultRule.Result.ruleList;
                                resultFinal.Msg = dataResultRule.Msg;
                                return resultFinal;
                            }

                            //更新先决条件列表
                            DataResult<OperationServiceParam> resultRules = this.SetRules(main, operationServiceParam);
                            if (resultRules.IsSuccess == false)
                            {
                                resultFinal.Msg = resultRules.Msg;
                                return resultFinal;
                            }
                            operationServiceParam = resultRules.Result;
                        }
                        else//为零件
                        {
                            Product product = operationServiceParam.product;
                            //校验先决条件
                            result = this.ValidateProcessRules(product, operationServiceParam);
                            if (result.IsSuccess == false)
                            {
                                resultFinal.Msg = result.Msg;
                                return resultFinal;
                            }
                            //更新先决条件列表
                            DataResult<OperationServiceParam> resultRules = this.SetRules(product, operationServiceParam);
                            if (resultRules.IsSuccess == false)
                            {
                                resultFinal.Msg = resultRules.Msg;
                                return resultFinal;
                            }
                            operationServiceParam = resultRules.Result;
                        }
                        resultFinal.Result = operationServiceParam;//更新完先决条件就加入返回值中
                        #endregion
                    }

                    #endregion

                    #region 4.判断加工先决条件是否全部通过
                    if (this.ValidateResult(operationServiceParam) == false)
                    {
                        resultFinal.Msg = "";
                        return resultFinal;
                    }
                    #endregion

                    #region 5.更新加工零件状态并发送设备指令
                    result = this.SaveAndSendOrder(operationServiceParam);
                    if (result.IsSuccess == false)
                    {
                        resultFinal.Msg = result.Msg;
                        return resultFinal;
                    }
                    #endregion

                    resultFinal.Result.isPass = true;
                    resultFinal.Msg = Resource.OperationSendSuccess;
                }

            }
            catch (Exception ex)
            {
                LogManager.LogHelper.Error(new LogInfo()
                {
                    ErrorInfo = ex,
                    Tag = ex.StackTrace,
                    Info = "加工操作-流程加工"
                });
                result.IsSuccess = false;
                resultFinal.Msg = Resource.SystemException;
            }

            return resultFinal;
        }
        

        /// <summary>
        /// 校验模具
        /// </summary>
        /// <returns></returns>
        public DataResult ValidateModel(OperationServiceParam operationServiceParam)
        {
            DataResult result = new DataResult();

            if (operationServiceParam.machineInfo.MODELS == null || operationServiceParam.machineInfo.MODELS.Count == 0)
            {
                result.Msg = Resource.NotHaveMoreModel;
                result.IsSuccess = false;
                return result;
            }
            //获取模具内容
            if ( !string.IsNullOrEmpty(operationServiceParam.model.MODELCODE))
            {
                operationServiceParam.model = operationServiceParam.machineInfo.MODELS.Find(m => m.MODELCODE == operationServiceParam.model.MODELCODE);
            }

            if ( operationServiceParam.model == null)
            {
                result.Msg = Resource.NotHaveThisModel;
                result.IsSuccess = false;
                return result;
            }

            

            #region 模架使用校验

            //2016-6-27 闫永刚 获取模架号加工状态信息
            //如果该模架正在加工中,那么不能进行操作,
            if (operationServiceParam.machineInfo.ISCONTROL == "3")
            {
                MainMolderStatus entity = new MainMolderStatusDAL().Get(
                    new MainMolderStatus()
                    {
                        MACHINECODDE = operationServiceParam.machineInfo.MACHINECODDE,
                        MOLDNUMBER = operationServiceParam.model.MODELCODE
                    }
                    );



                if (entity.OPERATIONFLAG.ToString() == EnumGeter.OPERATIONFLAG.BUSY.GetHashCode().ToString() 
                   )
                {
                    result.Msg = string.Format("模架{0}正在加工中,请等待加工完成或是手动放行!", operationServiceParam.model.MODELCODE);
                    result.IsSuccess = false;
                    return result; 
                }
            }

            #endregion

            ProcessRule roleModel = operationServiceParam.ruleList.Find(m=>m.RULETYPE==EnumGeter.RULETYPE.MODEL.GetHashCode().ToString());
            roleModel.RULECONTENTTEXT = operationServiceParam.model.MODELNAME;

            //加入模具对零件的校验
            if (operationServiceParam.model.ISVALIDATE.Equals(EnumGeter.YESORNO.YES.GetHashCode().ToString()))//当前模具有条件判断
            {
                //判断零件类别
                if (operationServiceParam.model.PRODUCTTYPE.Equals(EnumGeter.ProductType.benti.GetHashCode().ToString()))//如果是本体的话
                {
                    //一共预置了3个零件的属性条件
                    if (operationServiceParam.main != null)
                    {
                        #region  校验3个预制属性
                        if (string.IsNullOrEmpty(operationServiceParam.model.ATTRBUTE1) == false)
                        {
                            string value1 = operationServiceParam.main.GetType().GetProperty(operationServiceParam.model.ATTRBUTE1).GetValue(operationServiceParam.main, null).ToString();
                            if (value1.Equals(operationServiceParam.model.VALUE1) == false)
                            {
                                result.Msg = Resource.OperationFitModel;
                                return result;
                            }
                        }
                        if (string.IsNullOrEmpty(operationServiceParam.model.ATTRBUTE2) == false)
                        {
                            string value2 = operationServiceParam.main.GetType().GetProperty(operationServiceParam.model.ATTRBUTE2).GetValue(operationServiceParam.main, null).ToString();
                            if (value2.Equals(operationServiceParam.model.VALUE2) == false)
                            {
                                result.Msg = Resource.OperationFitModel;
                                return result;
                            }
                        }
                        if (string.IsNullOrEmpty(operationServiceParam.model.ATTRBUTE3) == false)
                        {
                            string value3 = operationServiceParam.main.GetType().GetProperty(operationServiceParam.model.ATTRBUTE3).GetValue(operationServiceParam.main, null).ToString();
                            if (value3.Equals(operationServiceParam.model.VALUE3) == false)
                            {
                                result.Msg = Resource.OperationFitModel;
                                return result;
                            }
                        }
                        #endregion

                        //设置先决条件为通过
                        ProcessRule rule = operationServiceParam.ruleList.Find(m => m.RULETYPE == EnumGeter.RULETYPE.MODEL.GetHashCode().ToString());
                        if (rule != null)//前置工序
                        {
                            SetResult(rule, true);
                        }
                    }
                    else//加工零件为本体但是却没有本体只有找表皮
                    {
                        Product product = operationServiceParam.productList.Find(m => m.PRODUCTTYPE == EnumGeter.ProductType.biaopi.GetHashCode().ToString());
                        if (product != null)
                        {
                            #region  校验3个预制属性
                            if (string.IsNullOrEmpty(operationServiceParam.model.ATTRBUTE1) == false)
                            {
                                string value1 = product.GetType().GetProperty(operationServiceParam.model.ATTRBUTE1).GetValue(product, null).ToString();
                                if (value1.Equals(operationServiceParam.model.VALUE1) == false)
                                {
                                    result.Msg = Resource.OperationFitModel;
                                    return result;
                                }
                            }
                            if (string.IsNullOrEmpty(operationServiceParam.model.ATTRBUTE2) == false)
                            {
                                string value2 = product.GetType().GetProperty(operationServiceParam.model.ATTRBUTE2).GetValue(product, null).ToString();
                                if (value2.Equals(operationServiceParam.model.VALUE2) == false)
                                {
                                    result.Msg = Resource.OperationFitModel;
                                    return result;
                                }
                            }
                            if (string.IsNullOrEmpty(operationServiceParam.model.ATTRBUTE3) == false)
                            {
                                string value3 = product.GetType().GetProperty(operationServiceParam.model.ATTRBUTE3).GetValue(product, null).ToString();
                                if (value3.Equals(operationServiceParam.model.VALUE3) == false)
                                {
                                    result.Msg = Resource.OperationFitModel;
                                    return result;
                                }
                            }
                            #endregion

                            //设置先决条件为通过
                            ProcessRule rule = operationServiceParam.ruleList.Find(m => m.RULETYPE == EnumGeter.RULETYPE.MODEL.GetHashCode().ToString());
                            if (rule != null)//前置工序
                            {
                                SetResult(rule, true);
                            }
                        }
                    }
                }
                else//为零件
                {
                    Product product = operationServiceParam.productList.Find(m => m.PRODUCTTYPE == operationServiceParam.model.PRODUCTTYPE);
                    if (product != null)
                    {
                        #region  校验3个预制属性
                        if (string.IsNullOrEmpty(operationServiceParam.model.ATTRBUTE1) == false)
                        {
                            string value1 = product.GetType().GetProperty(operationServiceParam.model.ATTRBUTE1).GetValue(product, null).ToString();
                            if (value1.Equals(operationServiceParam.model.VALUE1) == false)
                            {
                                result.Msg = Resource.OperationFitModel;
                                return result;
                            }
                        }
                        if (string.IsNullOrEmpty(operationServiceParam.model.ATTRBUTE2) == false)
                        {
                            string value2 = product.GetType().GetProperty(operationServiceParam.model.ATTRBUTE2).GetValue(product, null).ToString();
                            if (value2.Equals(operationServiceParam.model.VALUE2) == false)
                            {
                                result.Msg = Resource.OperationFitModel;
                                return result;
                            }
                        }
                        if (string.IsNullOrEmpty(operationServiceParam.model.ATTRBUTE3) == false)
                        {
                            string value3 = product.GetType().GetProperty(operationServiceParam.model.ATTRBUTE3).GetValue(product, null).ToString();
                            if (value3.Equals(operationServiceParam.model.VALUE3) == false)
                            {
                                result.Msg = Resource.OperationFitModel;
                                return result;
                            }
                        }
                        #endregion

                        //设置先决条件为通过
                        ProcessRule rule = operationServiceParam.ruleList.Find(m => m.RULETYPE == EnumGeter.RULETYPE.MODEL.GetHashCode().ToString());
                        if (rule != null)//前置工序
                        {
                            SetResult(rule, true);
                        }
                    }
                }
            }
            result.Msg = Resource.SuccessGetModel;
            result.IsSuccess = true; 
            return result;
        }


        public DataResult<Main> GetMainCode(Product entity)
        {
            DataResult<Main> result = new DataResult<Main>();

            Main main = new Main();
            string mainCode = "";
            PrintCode printcode = new MainDAL().GetMaxMainCode(entity.MATERIAL_CODE);
            if (string.IsNullOrEmpty(printcode.MAINCODE))
            {
                mainCode = "1";
            }
            else
            {
                mainCode = (Convert.ToInt32(mainCode) + 1) + "";
            }
            main.MAINCODE = "052 4XR" + mainCode.PadLeft(7, '0');
            main.MAINCODE = new FileCopyRecordDAL().GetBarcode(main.MAINCODE);

            result.Result = main;

            return result;

        }

        /// <summary>
        /// 填充传递参数
        /// </summary>
        /// <returns></returns>
        public DataResult GetParamModels(OperationServiceParam operationServiceParam)
        {
            DataResult result = new DataResult();
            try
            {
                #region 1. 获取当前设备工序所对应的工序类别
                string mainProductType = operationServiceParam.processSet.PRODUCTTYPE.ToString();
                //根据类别获取productBasic
                ProductBasic basic = new ProductBasicBLL().GetByCode(new ProductBasic { PRODUCTTYPE = mainProductType });
                if (basic == null)
                {
                    result.Msg = Resource.OperationProTypeError;
                    result.IsSuccess = false;
                    return result;
                }
                #endregion

                try
                {
                    if (operationServiceParam.machineInfo.PROCESSTYPE == EnumGeter.ProcessType.jiaozhu.GetHashCode().ToString())
                    {
                        //LogManager.LogHelper.Info(new LogInfo() { Info = "mainProductType=" + mainProductType.ToString() });
                        //LogManager.LogHelper.Info(new LogInfo() { Info = "ISPARENT=" + basic.ISPARENT.ToString() });
                        //LogManager.LogHelper.Info(new LogInfo() { Info = "operationServiceParam.main:" + (operationServiceParam.main == null ? "null" : " No null") });
                        //LogManager.LogHelper.Info(new LogInfo() { Info = "basic.ISPARENT:" + basic.ISPARENT.ToString() });
                        //LogManager.LogHelper.Info(new LogInfo() { Info = "PRODUCTISPARENT.yes:" + EnumGeter.PRODUCTISPARENT.yes.GetHashCode().ToString() });
                    }

                }
                catch (Exception)
                {
                    LogManager.LogHelper.Info(new LogInfo() { Info = "异常" });
                }
                
                #region 2.根据是否为父级标识,以及是否存在本体 ,判断是否新增本体数据
                //if (basic.ISPARENT.Equals(EnumGeter.PRODUCTISPARENT.yes.GetHashCode().ToString())
                //    && operationServiceParam.main == null)//是父级
                //LogManager.LogHelper.Info(new LogInfo() { Info = "operationServiceParam.main:" + (operationServiceParam.main == null ? "null" : " No null") });
                if (operationServiceParam.machineInfo.PROCESSTYPE == EnumGeter.ProcessType.jiaozhu.GetHashCode().ToString())
                {
                   
                    //闫永刚 2016-9-14 增加一个额外处理,浇注扫描表皮和骨架两个码,
                    //实际情况中个别时候出现两个表皮和一个骨架的情况,winform的校验有时候会失效,无法找到原因
                    //所以在这里加一段代码把第一个表皮或是第一个骨架去除
                    try
                    {
                        foreach (var p in operationServiceParam.productList)
                        {
                            LogManager.LogHelper.Info(new LogInfo() { Info = "PRODUCTOCDE:" + ((p.PRODUCTCODE != null ? p.PRODUCTCODE : "")) + "PRODUCTTYPE:" + ((p.PRODUCTTYPE != null ? p.PRODUCTTYPE : "")) });
                        }
                    }
                    catch (Exception ex)
                    {
                        LogManager.LogHelper.Info(new LogInfo() { Info = "异常" });
                    }

                    Main main = new Main();
                    main.PID = "";//新id
                    //获取骨架
                    Product pSk = operationServiceParam.productList.Find(m => m.PRODUCTTYPE == EnumGeter.ProductType.gujia.GetHashCode().ToString());
                    if (pSk == null)
                    {
                        result.Msg = Resource.OperationNotFoundGuJia;
                        result.IsSuccess = false;
                        return result;
                    }
                    main.SKID = pSk.PID;//骨架  
                    main.SKELETONCODE = pSk.PRODUCTCODE;//骨架条码
                    //获取表皮
                    Product pEP = operationServiceParam.productList.Find(m => m.PRODUCTTYPE == EnumGeter.ProductType.biaopi.GetHashCode().ToString());
                    if (pEP == null)
                    {
                        result.Msg = Resource.OperationNotFoundBiaoPi;
                        result.IsSuccess = false;
                        return result;
                    }
                    main.EID = pEP.PID;//表皮
                    main.EPIDERMISCODE = pEP.PRODUCTCODE;//表皮条码
                    main.HB = pEP.VAL3;//高低配
                    main.COLOR = pEP.VAL4;//颜色
                    main.MACHINECODDE = operationServiceParam.machineInfo.MACHINECODDE;
                    main.PROCESSSTATE = EnumGeter.OPERATESTATE.OPERATING.GetHashCode().ToString();
                    main.STATUS = EnumGeter.PRODUCTSTAUTS.QUALIFIED.GetHashCode().ToString();
                    main.CURRENTPROCESS = operationServiceParam.processSet.PROCESSTYPE;
                    main.COMPLETEFLAG = EnumGeter.COMPLETEFLAG.PROCESSING.GetHashCode().ToString();
                    main.PRODUCELINE = EnumGeter.PRODUCELINE.B9.ToString();
                    main.PRODUCESHIFTNAME = operationServiceParam.produceShift.PRODUCESHIFTNAME;
                    main.PRODUCESHIFTTCODE = operationServiceParam.produceShift.PRODUCESHIFTTCODE;
                    main.OUTFLAG = EnumGeter.OUTFLAG.INWAREHOUSE.GetHashCode().ToString();
                    main.CREATEUSER = this.LoginUser.UserID;
                    main.CREATEDATE = DateTime.Now;
                    main.UPDATEUSER = main.CREATEUSER;
                    main.UPDATEDATE = main.CREATEDATE;
                    operationServiceParam.main = main;
                }
                if (operationServiceParam.main != null)
                {
                    operationServiceParam.main.PROCESSSTATE = EnumGeter.OPERATESTATE.OPERATING.GetHashCode().ToString();
                }
                #endregion

                #region 判断是否装配,如果为装配那么需要生成装配条码
                if (operationServiceParam.processSet.PROCESSTYPE.Equals(EnumGeter.ProcessType.zongchengzhuangpei.GetHashCode().ToString()))
                {
                    //string mainCode = new MainDAL().GetMaxMainCode();
                    //if (string.IsNullOrEmpty(mainCode))
                    //{
                    //    mainCode = "1";
                    //}
                    PrintCode printCode = new MainDAL().GetMaxMainCode(operationServiceParam.mainOperation.MATERIAL_CODE);
                    string mainCode = "";
                    if (string.IsNullOrEmpty(printCode.MAINCODE))
                    {
                        mainCode = "1";
                    }
                    else
                    {
                        mainCode = (Convert.ToInt32(mainCode) + 1) + "";
                    }
                    operationServiceParam.main.MAINCODE = "052 4XR" + mainCode.PadLeft(7, '0');
                    operationServiceParam.main.MAINCODE = new FileCopyRecordDAL().GetBarcode(operationServiceParam.main.MAINCODE);
                    operationServiceParam.main.COMPLETETIME = DateTime.Now;
                    //调用打印方法
                    //string xmlPath = "../../XMLResources/Biaopi.xml";
                    //BarcodeLib.BarCodeGenerate generate = new BarcodeLib.BarCodeGenerate();
                    //generate.PrintBarCode(operationServiceParam.main.MAINCODE, xmlPath);
                }

                #endregion

                #region 3.处理零件与本体关联关系
                //处理零件
                //零件在判断先决条件的时候已做处理
                //处理本体与零件关系 
                List<MainProduct> mainProducts = new List<MainProduct>();
                if (operationServiceParam.main != null)
                {
                    foreach (Product item in operationServiceParam.productList)
                    {

                        MainProduct mainProduct = new MainProduct();
                        mainProduct.MID = "";
                        mainProduct.PDID = item.PID;
                        mainProduct.COUNT = item.useCount;
                        mainProduct.MOID = "";//加工记录pid
                        mainProduct.CREATEUSER = this.LoginUser.UserID;
                        mainProduct.CREATEDATE = DateTime.Now;
                        mainProduct.UPDATEUSER = mainProduct.CREATEUSER;
                        mainProduct.UPDATEDATE = mainProduct.CREATEDATE;
                        mainProducts.Add(mainProduct);
                    }
                }

                operationServiceParam.mainProductList = mainProducts;
                #endregion

                #region 4.处理生产记录
                //处理生产记录
                MainOperation mainOperation = new MainOperation();
                mainOperation.PID = "";
                mainOperation.PDID = "";//判断生产类别 如果是本体  或者零件
                if (operationServiceParam.processSet.PRODUCTTYPE.Equals(EnumGeter.ProductType.benti.GetHashCode().ToString()))
                {
                    mainOperation.PDID = operationServiceParam.main.PID;
                    mainOperation.PRODUCTCODE = operationServiceParam.main.EPIDERMISCODE;//采用表皮的条码

                    if(operationServiceParam.productList.Count>0)
                    {
                        List<Product> prolist = operationServiceParam.productList.OrderBy(o => o.PRODUCTCODE).ToList<Product>();
                        foreach (var p in prolist)
                        {
                            if (p.PRODUCTCODE != mainOperation.PRODUCTCODE)
                            {
                                mainOperation.PRODUCTCODESTR += p.PRODUCTCODE;
                                mainOperation.PRODUCTCODESTR += ":";
                            }
                        }

                        if (mainOperation.PRODUCTCODESTR.Length > 0)
                        {
                            mainOperation.PRODUCTCODESTR = mainOperation.PRODUCTCODESTR.Substring(0, mainOperation.PRODUCTCODESTR.Length - 1);
                        }
                    }
                }
                else
                {
                    //找到加工零件类别
                    Product p;
                    if (operationServiceParam.productList.Count > 1)
                    {
                        p = operationServiceParam.productList.Find(m => m.PRODUCTTYPE == operationServiceParam.processSet.PRODUCTTYPE.ToString());
                    }
                    else//为了风道设置
                    {
                        p = operationServiceParam.productList[0];
                        mainOperation.PRODUCTTYPE = p.PRODUCTTYPE;
                    }
                     
                    mainOperation.PDID = p.PID;
                    mainOperation.PRODUCTCODE = p.PRODUCTCODE;
                }
                if (string.IsNullOrEmpty(mainOperation.PRODUCTTYPE))
                {
                    mainOperation.PRODUCTTYPE = operationServiceParam.processSet.PRODUCTTYPE.ToString();
                }

                mainOperation.PROCESSTYPE = operationServiceParam.processSet.PROCESSTYPE.ToString();
                mainOperation.MACHINECODDE = operationServiceParam.machineInfo.MACHINECODDE;
                mainOperation.MACHINENAME = operationServiceParam.machineInfo.MACHINENAME;
                mainOperation.STATUS = EnumGeter.PRODUCTSTAUTS.QUALIFIED.GetHashCode().ToString();
                mainOperation.OPERATESTATE = EnumGeter.OPERATESTATE.OPERATING.GetHashCode().ToString();
                mainOperation.CURRENTPROCESS = operationServiceParam.processSet.PROCESSTYPE.ToString();
                mainOperation.PRODUCESHIFTNAME = operationServiceParam.produceShift.PRODUCESHIFTNAME;
                mainOperation.PRODUCESHIFTTCODE = operationServiceParam.produceShift.PRODUCESHIFTTCODE;
                mainOperation.MOLDNUMBER = operationServiceParam.machineInfo.MOLDNUMBER;
                if (string.IsNullOrEmpty(mainOperation.MOLDNUMBER ))
                {
                    mainOperation.MOLDNUMBER = "1";
                }
                mainOperation.CREATEUSER = this.LoginUser.UserID;
                mainOperation.CREATEDATE = DateTime.Now;
                mainOperation.UPDATEUSER = mainOperation.CREATEUSER;
                mainOperation.UPDATEDATE = mainOperation.CREATEDATE;
                mainOperation.PRODUCELINE = EnumGeter.PRODUCELINE.B9.ToString();
                //mainOperation.PRODUCELINE = EnumGeter.PRODUCELINE.B9.ToString();
                if (operationServiceParam.model != null)
                {
                    mainOperation.MODELSTATION = operationServiceParam.model.MODELCODE;//模具  
                }
                else
                {
                    mainOperation.MODELSTATION = "1";
                }

                operationServiceParam.mainOperation = mainOperation;
                #endregion


                #region 设置设备模架加工状态

                //2016-6-27 闫永刚
                //设置模架加工状态
                if (operationServiceParam.machineInfo.ISCONTROL == "3")
                {
                    MainMolderStatus mainMolderStatus = new MainMolderStatus();
                    mainMolderStatus.MACHINECODDE = operationServiceParam.machineInfo.MACHINECODDE;
                    mainMolderStatus.MOLDNUMBER = mainOperation.MOLDNUMBER;
                    mainMolderStatus.OPERATIONFLAG = Convert.ToInt32(EnumGeter.OPERATIONFLAG.BUSY.GetHashCode().ToString());
                    mainMolderStatus.BARCODE = "";

                    operationServiceParam.mainMolderStatus = mainMolderStatus;
                }
                
                #endregion

                result.IsSuccess = true;
            }
            catch (Exception ex)
            {
                result.IsSuccess = false;
                result.Msg = ex.Message;
                throw;
            }

            return result;
        }


        /// <summary>
        /// 插入信息(单表)
        /// </summary>
        /// <param name="">信息</param>
        /// <returns>插入行数</returns>
        public DataResult<int> MachineOperation(OperationServiceParam model)
        {
            DataResult<int> result = new DataResult<int>();

            int count = 0;
            using (IDataSession session = AppDataFactory.CreateMainSession())
            {
                try
                {
                    session.OpenCon();

                    #region 1. 更新插入主体表
                    MainDAL mainDAL = new MainDAL();
                    mainDAL.BaseSession = session;
                    if (model.main != null)
                    {
                        if (string.IsNullOrEmpty(model.main.PID))
                        {

                            model.main.PID = Guid.NewGuid().ToString();
                            model.main.CREATEUSER = this.LoginUser.UserID;
                            model.main.CREATEDATE = DateTime.Now;
                            model.main.UPDATEUSER = model.main.CREATEUSER;
                            model.main.UPDATEDATE = DateTime.Now;
                            count = mainDAL.Insert(model.main);

                            if (model.machineInfo.ISCONTROL == "3")
                            {
                                model.mainMolderStatus.BARCODE += model.main.SKELETONCODE;
                            }

                            
                        }
                        else
                        {
                            model.main.UPDATEUSER = model.main.CREATEUSER;
                            count = mainDAL.Update(model.main);
                        }

                        if (model.machineInfo.ISCONTROL == "3")
                        {
                            model.mainMolderStatus.BARCODE += model.main.EPIDERMISCODE;
                        }
                        
                        
                    }
                    #endregion

                    #region 2.补充更新零件的属性
                    //填充加工记录
                    if (model.mainOperation != null)
                    {
                        if (model.main != null)
                        {
                            model.mainOperation.PDID = model.main.PID;
                        }
                        else
                        {
                            model.mainOperation.PDID = model.productList[0].PID;
                        }
                        model.mainOperation.PID = Guid.NewGuid().ToString();
                        model.mainOperation.CREATEUSER = this.LoginUser.UserID;
                        model.mainOperation.CREATEDATE = DateTime.Now;
                        model.mainOperation.UPDATEUSER = model.mainOperation.CREATEUSER;
                        model.mainOperation.UPDATEDATE = DateTime.Now;
                    }
                    #endregion

                    #region 3.填充本体零件关系
                    if (model.mainProductList != null && model.mainProductList.Count > 0)
                    {
                        foreach (var item in model.mainProductList)
                        {
                            item.PID = Guid.NewGuid().ToString();
                            item.MID = model.main.PID;
                            item.MOID = model.mainOperation.PID;
                            item.CREATEUSER = this.LoginUser.UserID;
                            item.CREATEDATE = DateTime.Now;
                            item.UPDATEUSER = item.CREATEUSER;
                            item.UPDATEDATE = DateTime.Now;
                        }
                    }
                    #endregion

                    #region 4. 保存主体零件关系表
                    if (model.mainProductList != null && model.mainProductList.Count > 0)
                    {
                        MainProductDAL mainProductDAL = new MainProductDAL();
                        mainProductDAL.BaseSession = session;
                        count = mainProductDAL.Insert(model.mainProductList);
                    }
                    #endregion

                    #region 5.更新零件表
                    if (model.productList != null && model.productList.Count > 0)
                    {
                        ProductDAL productDAL = new ProductDAL();
                        productDAL.BaseSession = session;
                        count = productDAL.Update(model.productList);


                        if (model.machineInfo.ISCONTROL == "3")
                        {
                            foreach (var p in model.productList)
                            {
                                if (model.mainMolderStatus.BARCODE.Contains(p.PRODUCTCODE) == false)
                                {
                                    model.mainMolderStatus.BARCODE += p.PRODUCTCODE;
                                }
                            }
                        }
                    }
                    #endregion

                    #region 6. 插入记录表
                    MainOperationDAL mainOperationDAL = new MainOperationDAL();
                    mainOperationDAL.BaseSession = session;
                    count = mainOperationDAL.Insert(model.mainOperation);
                    #endregion

                    #region 更新模架加工状态

                    //2016-6-27 闫永刚
                    //更新模架加工状态

                    if (model.machineInfo.ISCONTROL == "3")
                    {
                        //2016-6-27 闫永刚
                        //更新
                        MainMolderStatusDAL mmdal = new MainMolderStatusDAL();
                        mmdal.BaseSession = session;

                        mmdal.Update(model.mainMolderStatus);

                    }
                    
                    #endregion

                    session.CommitTs();
                    result.Result = count;
                    result.IsSuccess = true; ;
                    result.Msg = Resource.MsgSuccess;
                }
                catch (Exception ex)
                {
                    session.RollbackTs();
                    LogManager.LogHelper.Error(new LogInfo()
                    {
                        ErrorInfo = ex,
                        Tag = ex.StackTrace,
                        Info = "加工操作保存发送-插入信息"
                    });
                    result.IsSuccess = false;
                    result.Msg = Resource.SystemException;
                    throw;
                }
            }
            return result;
        }

        #region 放行
        /// <summary>
        /// 放行零件
        /// </summary>
        /// <param name="partCode">传递参数</param>
        /// <returns></returns>
        public DataResult SetPassProcess(Product product)
        {
            DataResult result = new DataResult();
            try
            {
                //获取零件信息
                Main main = new Main();
                MainOperation mainOperation = new MainOperation();
                product = new ProductBLL().GetByCondition(product);
                if (product == null)//没有找到零件
                {
                    result.IsSuccess = false;
                    result.Msg = Resource.OperationProNotFound;
                    return result;
                }

                if (product.PRODUCTTYPE.Equals(EnumGeter.ProductType.biaopi.GetHashCode().ToString()) && product.USINGSTATE.Equals(EnumGeter.USINGSTATE.UNUSED.GetHashCode().ToString()) ==  false)
                {
                    #region 该零件为本体

                    product.IsMain = true;

                    main.publicCode = product.PRODUCTCODE.Trim();
                    main = new MainBLL().GetByCondition(main);

                    mainOperation.PDID = main.PID;
                    mainOperation.PROCESSTYPE = main.CURRENTPROCESS;
                    mainOperation.OPERATESTATE = EnumGeter.OPERATESTATE.OPERATING.GetHashCode().ToString();
                    mainOperation = this.GetByCondition(mainOperation);
                    if (mainOperation == null)//出错没有找到生产记录
                    {
                        result.IsSuccess = false;
                        result.Msg = "没有找到生产记录,请先进行撤销操作!";
                        return result;
                    }

                    if (mainOperation.OPERATESTATE.Equals(EnumGeter.OPERATESTATE.OPERATING.GetHashCode().ToString()) == false)//出错不是加工中
                    {
                        result.IsSuccess = false;
                        result.Msg = Resource.NotInOperating;
                        return result;
                    }

                    //1.更新零件状态
                    //获取当前零件类别的工序
                    List<ProcessSet> listProcess = new ProcessSetBLL().GetAllList(new ProcessSet { PRODUCTTYPE = EnumGeter.ProductType.benti.GetHashCode().ToString() });
                    listProcess.Sort((m, n) => { return m.PROCESSINDEX.CompareTo(n.PROCESSINDEX); });
                    int currentIndex = listProcess.FindIndex(m => m.PROCESSTYPE == main.CURRENTPROCESS);
                    if (currentIndex >= listProcess.Count-1)//最后一道工序,做完结操作
                    {
                        main.COMPLETEFLAG = EnumGeter.COMPLETEFLAG.COMPLETED.GetHashCode().ToString();
                        main.PROCESSSTATE = EnumGeter.OPERATESTATE.RELEASED.GetHashCode().ToString();
                    }
                    else//设置到下一道工序
                    {
                        main.CURRENTPROCESS = listProcess[currentIndex + 1].PROCESSTYPE;
                        main.PROCESSSTATE = EnumGeter.OPERATESTATE.RELEASED.GetHashCode().ToString();
                    }


                    //2.更新生产记录
                    mainOperation.OPERATESTATE = EnumGeter.OPERATESTATE.RELEASED.GetHashCode().ToString();
                    mainOperation.OPERATEDDATE = DateTime.Now;
                    #endregion
                }
                else
                {
                    #region 该零件为零件
                    product.IsMain = false;
                    mainOperation.PDID = product.PID;
                    mainOperation.PROCESSTYPE = product.CURRENTPROCESS;
                    mainOperation.OPERATESTATE = EnumGeter.OPERATESTATE.OPERATING.GetHashCode().ToString();
                    mainOperation = this.GetByCondition(mainOperation);
                    if (mainOperation == null)//出错没有找到生产记录
                    {
                        result.IsSuccess = false;
                        result.Msg = "没有找到生产记录,请先进行撤销操作!";
                        return result;
                    }

                    if (mainOperation.OPERATESTATE.Equals(EnumGeter.OPERATESTATE.OPERATING.GetHashCode().ToString()) == false)//出错不是加工中
                    {
                        result.IsSuccess = false;
                        result.Msg = Resource.NotInOperating;
                        return result;
                    }

                    //1.更新零件状态
                    //获取当前零件类别的工序
                    List<ProcessSet> listProcess = new ProcessSetBLL().GetAllList(new ProcessSet { PRODUCTTYPE = product.PRODUCTTYPE });
                    listProcess.Sort((m, n) => { return m.PROCESSINDEX.CompareTo(n.PROCESSINDEX); });
                    int currentIndex = listProcess.FindIndex(m => m.PROCESSTYPE == product.CURRENTPROCESS);
                    if (currentIndex >= listProcess.Count)//最后一道工序,做完结操作
                    {
                        if (product.CAPACITY <= product.USINGCOUNT)
                        {
                            product.USINGSTATE = EnumGeter.USINGSTATE.USED.GetHashCode().ToString();
                        }
                    }
                    else//设置到下一道工序
                    {
                        product.CURRENTPROCESS = listProcess[currentIndex + 1].PROCESSTYPE;
                    }


                    //2.更新生产记录
                    mainOperation.OPERATESTATE = EnumGeter.OPERATESTATE.RELEASED.GetHashCode().ToString();
                    mainOperation.OPERATEDDATE = DateTime.Now;
                    #endregion
                }

                using (IDataSession session = AppDataFactory.CreateMainSession())
                {

                    session.OpenCon();
                    int count = 0;
                    #region 1. 更新插入主体表
                    if (product.IsMain)
                    {
                        count = new MainDAL().Update(main);
                    }
                    else
                    {
                        count = new ProductDAL().Update(product);
                    }

                    #endregion

                    #region 2. 更新记录表

                    MainOperationDAL mainOperationDAL = new MainOperationDAL();
                    mainOperationDAL.BaseSession = session;
                    count = mainOperationDAL.Update(mainOperation);

                    #endregion

                    #region 

                    //2016-06-27 闫永刚
                    //设置模架状态为空闲

                    MainMolderStatusDAL mmdal = new MainMolderStatusDAL();
                    mmdal.BaseSession = session;
                    mmdal.Update(new MainMolderStatus() { MACHINECODDE = mainOperation.MACHINECODDE, OPERATIONFLAG = Convert.ToInt32(EnumGeter.OPERATIONFLAG.FREE.GetHashCode().ToString()), MOLDNUMBER = mainOperation.MOLDNUMBER ,BARCODE=""});

                    #endregion

                    session.CommitTs();
                    result.IsSuccess = true;
                    result.Msg = Resource.SetPassSuccess;
                }
            }
            catch (Exception ex)
            {
                LogManager.LogHelper.Error(new LogInfo()
                {
                    ErrorInfo = ex,
                    Tag = ex.StackTrace,
                    Info = "零件工序放行"
                });
                result.IsSuccess = false;
                result.Msg = Resource.SystemException;
                throw;
            }

            return result;
        }


        public DataResult SetPunchingPassProcess()
        {
            DataResult result = new DataResult();
            try
            {
                //获取零件信息
                Main main = new Main();
                main.CURRENTPROCESS = EnumGeter.ProcessType.chongqie.GetHashCode().ToString();
                main.PROCESSSTATE = EnumGeter.OPERATESTATE.OPERATING.GetHashCode().ToString();
                main = new MainBLL().GetByCondition(main);
                if (main != null && string.IsNullOrEmpty(main.PID) == false)
                {
                    main = new MainBLL().Get(main);
                }

                LogManager.LogHelper.Info(new LogInfo() { Info = "t1" });


                MainOperation mainOperation = new MainOperation();

                #region 该零件为本体

                mainOperation.PDID = main.PID;
                mainOperation.PROCESSTYPE = main.CURRENTPROCESS;
                mainOperation.OPERATESTATE = EnumGeter.OPERATESTATE.OPERATING.GetHashCode().ToString();
                mainOperation = this.GetByCondition(mainOperation);
                if (mainOperation == null)//出错没有找到生产记录
                {
                    result.IsSuccess = false;
                    result.Msg = "没有找到生产记录,请先进行撤销操作!";
                    return result;
                }

                if (mainOperation.OPERATESTATE.Equals(EnumGeter.OPERATESTATE.OPERATING.GetHashCode().ToString()) == false)//出错不是加工中
                {
                    result.IsSuccess = false;
                    result.Msg = Resource.NotInOperating;
                    return result;
                }

                //1.更新零件状态
                //获取当前零件类别的工序
                List<ProcessSet> listProcess = new ProcessSetBLL().GetAllList(new ProcessSet { PRODUCTTYPE = EnumGeter.ProductType.benti.GetHashCode().ToString() });
                listProcess.Sort((m, n) => { return m.PROCESSINDEX.CompareTo(n.PROCESSINDEX); });
                int currentIndex = listProcess.FindIndex(m => m.PROCESSTYPE == main.CURRENTPROCESS);
                if (currentIndex >= listProcess.Count - 1)//最后一道工序,做完结操作
                {
                    main.COMPLETEFLAG = EnumGeter.COMPLETEFLAG.COMPLETED.GetHashCode().ToString();
                    main.PROCESSSTATE = EnumGeter.OPERATESTATE.RELEASED.GetHashCode().ToString();
                }
                else//设置到下一道工序
                {
                    main.CURRENTPROCESS = listProcess[currentIndex + 1].PROCESSTYPE;
                    main.PROCESSSTATE = EnumGeter.OPERATESTATE.RELEASED.GetHashCode().ToString();
                }


                //2.更新生产记录
                mainOperation.OPERATESTATE = EnumGeter.OPERATESTATE.COMPLETED.GetHashCode().ToString();
                mainOperation.OPERATEDDATE = DateTime.Now;

                #endregion

                LogManager.LogHelper.Info(new LogInfo() { Info = "t2" });

                using (IDataSession session = AppDataFactory.CreateMainSession())
                {

                    session.OpenCon();
                    int count = 0;
                    #region 1. 更新插入主体表

                    count = new MainDAL().Update(main);

                    #endregion

                    #region 2. 更新记录表

                    MainOperationDAL mainOperationDAL = new MainOperationDAL();
                    mainOperationDAL.BaseSession = session;
                    count = mainOperationDAL.Update(mainOperation);

                    #endregion

                    #region

                    //2016-06-27 闫永刚
                    //设置模架状态为空闲

                    MainMolderStatusDAL mmdal = new MainMolderStatusDAL();
                    mmdal.BaseSession = session;
                    mmdal.Update(new MainMolderStatus() { MACHINECODDE = mainOperation.MACHINECODDE, OPERATIONFLAG = Convert.ToInt32(EnumGeter.OPERATIONFLAG.FREE.GetHashCode().ToString()), MOLDNUMBER = mainOperation.MOLDNUMBER, BARCODE = "" });

                    #endregion

                    #region

                    PunchParameter parameter = new PunchParameter(mainOperation.PRODUCTCODE);
                    parameter.PID = Guid.NewGuid().ToString();
                    parameter.MOID = mainOperation.PID;
                    parameter.PDID = mainOperation.PDID;
                    parameter.PRODUCTTYPE = mainOperation.PRODUCTTYPE;
                    parameter.PRODUCTCODE = mainOperation.PRODUCTCODE;
                    parameter.MACHINECODDE = mainOperation.MACHINECODDE;
                    parameter.MACHINENAME = mainOperation.MACHINENAME;
                    parameter.CREATEDATE = System.DateTime.Now;

                    //PunchParameterDAL paraDal = new PunchParameterDAL();
                    //paraDal.BaseSession = session;
                    //paraDal.Insert(parameter);

                    #endregion

                    session.CommitTs();
                    result.IsSuccess = false;
                    result.Msg = "自动放行冲切工序,请再次扫描该条码!";
                }
            }
            catch (Exception ex)
            {
                LogManager.LogHelper.Error(new LogInfo()
                {
                    ErrorInfo = ex,
                    Tag = ex.StackTrace,
                    Info = "Punch realse unpunch exception"
                });
                result.IsSuccess = false;
                result.Msg = "冲切工序已自动放行,请再次扫描该条码!";
                throw;
            }

            return result;
        }

        public DataResult SetPunchingPassProcess(Main model)
        {
            DataResult result = new DataResult();
            try
            {
                //获取零件信息
                Main main = new Main();
                main = new MainBLL().Get(model);


                MainOperation mainOperation = new MainOperation();

                #region 该零件为本体

                mainOperation.PDID = main.PID;
                mainOperation.PROCESSTYPE = main.CURRENTPROCESS;
                mainOperation.OPERATESTATE = EnumGeter.OPERATESTATE.OPERATING.GetHashCode().ToString();
                mainOperation = this.GetByCondition(mainOperation);
                if (mainOperation == null)//出错没有找到生产记录
                {
                    result.IsSuccess = false;
                    result.Msg = "没有找到生产记录,请先进行撤销操作!";
                    return result;
                }

                if (mainOperation.OPERATESTATE.Equals(EnumGeter.OPERATESTATE.OPERATING.GetHashCode().ToString()) == false)//出错不是加工中
                {
                    result.IsSuccess = false;
                    result.Msg = Resource.NotInOperating;
                    return result;
                }

                //1.更新零件状态
                //获取当前零件类别的工序
                List<ProcessSet> listProcess = new ProcessSetBLL().GetAllList(new ProcessSet { PRODUCTTYPE = EnumGeter.ProductType.benti.GetHashCode().ToString() });
                listProcess.Sort((m, n) => { return m.PROCESSINDEX.CompareTo(n.PROCESSINDEX); });
                int currentIndex = listProcess.FindIndex(m => m.PROCESSTYPE == main.CURRENTPROCESS);
                if (currentIndex >= listProcess.Count - 1)//最后一道工序,做完结操作
                {
                    main.COMPLETEFLAG = EnumGeter.COMPLETEFLAG.COMPLETED.GetHashCode().ToString();
                    main.PROCESSSTATE = EnumGeter.OPERATESTATE.RELEASED.GetHashCode().ToString();
                }
                else//设置到下一道工序
                {
                    main.CURRENTPROCESS = listProcess[currentIndex + 1].PROCESSTYPE;
                    main.PROCESSSTATE = EnumGeter.OPERATESTATE.RELEASED.GetHashCode().ToString();
                }


                //2.更新生产记录
                mainOperation.OPERATESTATE = EnumGeter.OPERATESTATE.COMPLETED.GetHashCode().ToString();
                mainOperation.OPERATEDDATE = DateTime.Now;

                #endregion

                using (IDataSession session = AppDataFactory.CreateMainSession())
                {

                    session.OpenCon();
                    int count = 0;
                    #region 1. 更新插入主体表

                    count = new MainDAL().Update(main);
                    #endregion

                    #region 2. 更新记录表

                    MainOperationDAL mainOperationDAL = new MainOperationDAL();
                    mainOperationDAL.BaseSession = session;
                    count = mainOperationDAL.Update(mainOperation);

                    #endregion

                    #region

                    //2016-06-27 闫永刚
                    //设置模架状态为空闲

                    MainMolderStatusDAL mmdal = new MainMolderStatusDAL();
                    mmdal.BaseSession = session;
                    mmdal.Update(new MainMolderStatus() { MACHINECODDE = mainOperation.MACHINECODDE, OPERATIONFLAG = Convert.ToInt32(EnumGeter.OPERATIONFLAG.FREE.GetHashCode().ToString()), MOLDNUMBER = mainOperation.MOLDNUMBER, BARCODE = "" });


                    #endregion

                    #region

                    PunchParameter parameter = new PunchParameter(mainOperation.PRODUCTCODE);
                    parameter.PID = Guid.NewGuid().ToString();
                    parameter.MOID = mainOperation.PID;
                    parameter.PDID = mainOperation.PDID;
                    parameter.PRODUCTTYPE = mainOperation.PRODUCTTYPE;
                    parameter.PRODUCTCODE = mainOperation.PRODUCTCODE;
                    parameter.MACHINECODDE = mainOperation.MACHINECODDE;
                    parameter.MACHINENAME = mainOperation.MACHINENAME;
                    parameter.CREATEDATE = System.DateTime.Now;

                    //PunchParameterDAL paraDal = new PunchParameterDAL();
                    //paraDal.BaseSession = session;
                    //paraDal.Insert(parameter);

                    #endregion

                    session.CommitTs();
                    result.IsSuccess = false;
                    result.Msg = "自动放行冲切工序,请再次扫描该条码进行铣削操作!";
                }
            }
            catch (Exception ex)
            {
                LogManager.LogHelper.Error(new LogInfo()
                {
                    ErrorInfo = ex,
                    Tag = ex.StackTrace,
                    Info = "Mill realse UnPunch exception"
                });
                result.IsSuccess = false;
                result.Msg = Resource.SystemException + "Mill realse UnPunch exception";
                throw;
            }

            return result;
        }

        #endregion

        #region 撤销加工
        /// <summary>
        /// 撤销加工
        /// </summary>
        /// <param name="partCode">传递参数</param>
        /// <returns></returns>
        public DataResult SetRecovery(Product product)
        {
            DataResult result = new DataResult();

            try
            {
                //获取零件信息
                Main main = new Main();
                MainOperation mainOperation = new MainOperation();
                product = new ProductBLL().GetByCondition(product);
                if (product == null)//没有找到零件
                {
                    result.IsSuccess = false;
                    result.Msg = Resource.OperationProNotFound;
                    return result;
                }

                if (product.PRODUCTTYPE.Equals(EnumGeter.ProductType.biaopi.GetHashCode().ToString()) && product.USINGSTATE.Equals(EnumGeter.USINGSTATE.UNUSED.GetHashCode().ToString()) == false)
                {
                    #region 该零件为本体

                    product.IsMain = true;

                    main.publicCode = product.PRODUCTCODE.Trim();
                    main = new MainBLL().GetByCondition(main);

                    mainOperation.PDID = main.PID;
                    mainOperation.PROCESSTYPE = main.CURRENTPROCESS;
                    mainOperation.OPERATESTATE = EnumGeter.OPERATESTATE.OPERATING.GetHashCode().ToString();
                    mainOperation = this.GetByCondition(mainOperation);
                    if (mainOperation == null)//出错没有找到生产记录
                    {
                        result.IsSuccess = false;
                        result.Msg = Resource.NotHaveOperation;
                        //return result;
                    }
                    else
                    {
                        if (mainOperation.OPERATESTATE.Equals(EnumGeter.OPERATESTATE.OPERATING.GetHashCode().ToString()) == false)//出错不是加工中
                        {
                            result.IsSuccess = false;
                            result.Msg = Resource.NotInOperating;
                            return result;
                        }
                    }

                    #endregion
                }
                else
                {
                    #region 该零件为零件
                    product.IsMain = false;
                    mainOperation.PDID = product.PID;
                    mainOperation.PROCESSTYPE = product.CURRENTPROCESS;
                    mainOperation.OPERATESTATE = EnumGeter.OPERATESTATE.OPERATING.GetHashCode().ToString();
                    mainOperation = this.GetByCondition(mainOperation);
                    if (mainOperation == null)//出错没有找到生产记录
                    {
                        result.IsSuccess = false;
                        result.Msg = Resource.NotHaveOperation;
                        return result;
                    }
                    else
                    {
                        if (mainOperation.OPERATESTATE.Equals(EnumGeter.OPERATESTATE.OPERATING.GetHashCode().ToString()) == false)//出错不是加工中
                        {
                            result.IsSuccess = false;
                            result.Msg = Resource.NotInOperating;
                            //return result;
                        }
                    }
                    #endregion
                }

                using (IDataSession session = AppDataFactory.CreateMainSession())
                {

                    session.OpenCon();
                    MainOperationDAL mainOpDal = new MainOperationDAL();
                    mainOpDal.BaseSession = session;
                    MainProductDAL mainProDal = new MainProductDAL();
                    mainProDal.BaseSession = session;
                    ProductDAL proDal = new ProductDAL();
                    proDal.BaseSession = session;

                    //获取零件关系表
                    List<MainProduct> listMainPro = mainProDal.GetList(new MainProduct { MOID = mainOperation.PID });
                    if (listMainPro.Count > 0)
                    {
                        foreach (MainProduct item in listMainPro)
                        {
                            Product pro = proDal.Get(new Product { PID = item.PDID });
                            if (pro != null)
                            {
                                pro.USINGCOUNT = pro.USINGCOUNT - item.COUNT;
                                if (pro.USINGCOUNT == 0)
                                {
                                    pro.USINGSTATE = EnumGeter.USINGSTATE.UNUSED.GetHashCode().ToString();
                                }
                                else
                                {
                                    pro.USINGSTATE = EnumGeter.USINGSTATE.USING.GetHashCode().ToString();
                                }
                                proDal.Update(pro);//更新零件
                            }
                            //删除零件关系
                            mainProDal.Delete(item);
                        }
                    }
                    //删除加工记录

                    if (mainOperation != null)
                    {
                        mainOpDal.Delete(mainOperation);
                    }
                    
                    
                    if (product.IsMain)
                    {
                        //更新本体状态
                        MainDAL mainDal = new MainDAL();
                        mainDal.BaseSession = session;
                        if (main.CURRENTPROCESS.Equals(EnumGeter.ProcessType.jiaozhu.GetHashCode().ToString()))
                        {
                             mainDal.Delete(main);
                        }
                        else
                        {
                            main.PROCESSSTATE = "1";
                            mainDal.Update(main);
                        }
                    }

                    #region 更新设备模架的加工状态为空闲

                    //2016-6-27 闫永刚
                    //设置模架状态为空闲

                    MainMolderStatusDAL mmdal = new MainMolderStatusDAL();
                    mmdal.BaseSession = session;
                    mmdal.Update(new MainMolderStatus() { MACHINECODDE = mainOperation.MACHINECODDE, OPERATIONFLAG = Convert.ToInt32(EnumGeter.OPERATIONFLAG.FREE.GetHashCode().ToString()), MOLDNUMBER = mainOperation.MOLDNUMBER, BARCODE = "" });

                    #endregion

                    session.CommitTs();
                    result.IsSuccess = true;
                    result.Msg = "撤销成功";
                }
            }
            catch (Exception ex)
            {
                LogManager.LogHelper.Error(new LogInfo()
                {
                    ErrorInfo = ex,
                    Tag = ex.StackTrace,
                    Info = "零件撤销"
                });
                result.IsSuccess = false;
                result.Msg = Resource.SystemException;
                throw;
            }

            return result;
        }
        #endregion

        #region 跳到下一工序不存在加工参数
        /// <summary>
        /// 零件
        /// </summary>
        /// <param name="partCode">传递参数</param>
        /// <returns></returns>
        public DataResult SetPassProcessToNext(Product product)
        {
            DataResult result = new DataResult();
            try
            {
                //获取零件信息
                Main main = new Main();
                MainOperation mainOperation = new MainOperation();
                product = new ProductBLL().GetByCondition(product);
                if (product == null)//没有找到零件
                {
                    result.IsSuccess = false;
                    result.Msg = Resource.OperationProNotFound;
                    return result;
                }

                if (product.PRODUCTTYPE.Equals(EnumGeter.ProductType.biaopi.GetHashCode().ToString()) 
                    && product.USINGSTATE.Equals(EnumGeter.USINGSTATE.USED.GetHashCode().ToString())
                    )
                {
                    #region 该零件为本体

                    product.IsMain = true;

                    main.publicCode = product.PRODUCTCODE.Trim();
                    main = new MainBLL().GetByCondition(main);

                    mainOperation.PDID = main.PID;
                    mainOperation.PROCESSTYPE = main.CURRENTPROCESS;
                    mainOperation.OPERATESTATE = EnumGeter.OPERATESTATE.OPERATING.GetHashCode().ToString();
                    mainOperation = this.GetByCondition(mainOperation);
                    if (mainOperation == null)//出错没有找到生产记录
                    {
                        result.IsSuccess = false;
                        result.Msg = "没有找到生产记录,请先进行撤销操作!";
                        return result;
                    }

                    if (mainOperation.OPERATESTATE.Equals(EnumGeter.OPERATESTATE.OPERATING.GetHashCode().ToString()) == false)//出错不是加工中
                    {
                        result.IsSuccess = false;
                        result.Msg = Resource.NotInOperating;
                        return result;
                    }

                    //1.更新零件状态
                    //获取当前零件类别的工序
                    List<ProcessSet> listProcess = new ProcessSetBLL().GetAllList(new ProcessSet { PRODUCTTYPE = EnumGeter.ProductType.benti.GetHashCode().ToString() });
                    listProcess.Sort((m, n) => { return m.PROCESSINDEX.CompareTo(n.PROCESSINDEX); });
                    int currentIndex = listProcess.FindIndex(m => m.PROCESSTYPE == main.CURRENTPROCESS);
                    if (currentIndex >= listProcess.Count - 1)//最后一道工序,做完结操作
                    {
                        main.COMPLETEFLAG = EnumGeter.COMPLETEFLAG.COMPLETED.GetHashCode().ToString();
                        main.PROCESSSTATE = EnumGeter.OPERATESTATE.RELEASED.GetHashCode().ToString();
                    }
                    else//设置到下一道工序
                    {
                        main.CURRENTPROCESS = listProcess[currentIndex + 1].PROCESSTYPE;
                        main.PROCESSSTATE = EnumGeter.OPERATESTATE.RELEASED.GetHashCode().ToString();
                    }


                    //2.更新生产记录
                    mainOperation.OPERATESTATE = EnumGeter.OPERATESTATE.COMPLETED.GetHashCode().ToString();
                    mainOperation.OPERATEDDATE = DateTime.Now;
                    #endregion
                }
                else
                {
                    #region 该零件为零件
                    product.IsMain = false;
                    mainOperation.PDID = product.PID;
                    mainOperation.PROCESSTYPE = product.CURRENTPROCESS;
                    mainOperation.OPERATESTATE = EnumGeter.OPERATESTATE.OPERATING.GetHashCode().ToString();
                    mainOperation = this.GetByCondition(mainOperation);
                    if (mainOperation == null)//出错没有找到生产记录
                    {
                        result.IsSuccess = false;
                        result.Msg = "没有找到生产记录,请先进行撤销操作!";
                        return result;
                    }

                    if (mainOperation.OPERATESTATE.Equals(EnumGeter.OPERATESTATE.OPERATING.GetHashCode().ToString()) == false)//出错不是加工中
                    {
                        result.IsSuccess = false;
                        result.Msg = Resource.NotInOperating;
                        return result;
                    }

                    //1.更新零件状态
                    //获取当前零件类别的工序
                    List<ProcessSet> listProcess = new ProcessSetBLL().GetAllList(new ProcessSet { PRODUCTTYPE = product.PRODUCTTYPE });
                    listProcess.Sort((m, n) => { return m.PROCESSINDEX.CompareTo(n.PROCESSINDEX); });
                    int currentIndex = listProcess.FindIndex(m => m.PROCESSTYPE == product.CURRENTPROCESS);
                    if (currentIndex >= listProcess.Count)//最后一道工序,做完结操作
                    {
                        if (product.CAPACITY <= product.USINGCOUNT)
                        {
                            product.USINGSTATE = EnumGeter.USINGSTATE.USED.GetHashCode().ToString();
                        }
                    }
                    else//设置到下一道工序
                    {
                        product.CURRENTPROCESS = listProcess[currentIndex + 1].PROCESSTYPE;
                    }


                    //2.更新生产记录
                    mainOperation.OPERATESTATE = EnumGeter.OPERATESTATE.COMPLETED.GetHashCode().ToString();
                    mainOperation.OPERATEDDATE = DateTime.Now;
                    #endregion
                }

                using (IDataSession session = AppDataFactory.CreateMainSession())
                {

                    session.OpenCon();
                    int count = 0;
                    #region 1. 更新插入主体表
                    if (product.IsMain)
                    {
                        count = new MainDAL().Update(main);
                    }
                    else
                    {
                        count = new ProductDAL().Update(product);
                    }

                    #endregion

                    #region 2. 更新记录表
                    MainOperationDAL mainOperationDAL = new MainOperationDAL();
                    mainOperationDAL.BaseSession = session;
                    count = mainOperationDAL.Update(mainOperation);
                    #endregion

                    session.CommitTs();
                    result.IsSuccess = true;
                    result.Msg = Resource.SetPassSuccess;
                }
            }
            catch (Exception ex)
            {
                LogManager.LogHelper.Error(new LogInfo()
                {
                    ErrorInfo = ex,
                    Tag = ex.StackTrace,
                    Info = "零件工序放行"
                });
                result.IsSuccess = false;
                result.Msg = Resource.SystemException;
                throw;
            }

            return result;
        }
        #endregion

        #region 获取加工记录列表(WEB根据工序查找设备加工参数)

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="condition">条件</param>
        /// <param name="page">数据页</param>
        /// <returns>数据页</returns>
        public DataResult<DataPage> GetListWithParameterForWeb(MainOperation condition, DataPage page)
        {
            DataResult<DataPage> dataResult = new DataResult<DataPage>();
            try
            {
                #region 获得加工参数标准值
                var conditionPParameter = new ProcessParameter
                {
                    WORKCELL_CODE=condition.WORKCELL_CODE,
                };

                
                var listPParameter = new ProcessParameterDAL().GetList(conditionPParameter);

                //如果没有获取到参数,则无参数字段显示
                if (listPParameter == null || listPParameter.Count == 0 || string.IsNullOrEmpty(condition.WORKCELL_CODE))
                {
                    dataResult.Result = new MainOperationDAL().GetListWithOutParameter(condition, page);
                }
                #endregion

                #region 获得加工记录及加工参数
                else
                {
                    condition.SelectCollumns = String.Join(",", listPParameter.Select(o => o.PARANAME));
                    condition.PARATABLENAME = listPParameter.FirstOrDefault().PARATABLENAME;
                    dataResult.Result = new MainOperationDAL().GetListWithParameter(condition, page);
                }
                  
                if (dataResult.Result.Result == null)
                {
                    dataResult.IsSuccess = false;
                    dataResult.Msg = QMAPP.FJC.Entity.Resource.NothingData;
                    dataResult.Result.Result = new DataTable();
                    return dataResult;
                }

                DataTable dtResult = dataResult.Result.Result as DataTable;

                DictManageBLL dictColumnName = new DictManageBLL(DictKind.MAINOPERATIONSEARCHFORM);
                DictManageBLL dictProcessType = new DictManageBLL(DictKind.PROCESSTYPE);
                DictManageBLL dictProductType = new DictManageBLL(DictKind.PRODUCTTYPE);
                DictManageBLL dictLJStatus = new DictManageBLL(DictKind.LJSTATUS);
                DictManageBLL dictOperateState = new DictManageBLL(DictKind.OPERATESTATE);
                DictManageBLL dictPSStatus = new DictManageBLL(DictKind.PRODUCTSTATUS);

                IList<DataColumn> listDelColumn = new List<DataColumn>();

                //转换枚举描述
                foreach (DataRow item in dtResult.Rows)
                {
                    //item["PROCESSTYPE"] = dictProcessType.GetDictValue(item["PROCESSTYPE"].ToString());
                    //item["PRODUCTTYPE"] = dictProductType.GetDictValue(item["PRODUCTTYPE"].ToString());
                    item["STATUS"] = dictPSStatus.GetDictValue(item["STATUS"].ToString());
                    item["OPERATESTATE"] = dictOperateState.GetDictValue(item["OPERATESTATE"].ToString()); 
                    //因为日期类型转成json绑定到页面显示格式错误,所以在datatable加上两个字符串型的操作时间和加工完成时间用于显示在页面上
                    if (!string.IsNullOrEmpty(item["OPERATEDDATESTR"].ToString()))
                    {
                        item["OPERATEDDATE"] = (Convert.ToDateTime(item["OPERATEDDATESTR"].ToString())).ToString("yyyy-MM-dd HH:mm:ss").Replace('/','-');
                    }
                    if (!string.IsNullOrEmpty(item["CREATEDATESTR"].ToString()))
                    {
                        item["CREATEDATE"] = Convert.ToDateTime(item["CREATEDATESTR"].ToString()).ToString("yyyy-MM-dd HH:mm:ss");
                    }
                }
                 
                //设置标题
                foreach (var item in dtResult.Columns.Cast<DataColumn>())
                {
                    if (item.ColumnName == "OPERATEDDATE" || item.ColumnName == "CREATEDATE")
                    {
                        //移除原来datetime类型的OPERATEDDATE、CREATEDATE
                        //listDelColumn.Add(item);
                    }
                    else
                    {
                        var strColumnName = dictColumnName.GetDictValue(item.ColumnName);
                        if (string.IsNullOrEmpty(strColumnName))
                        {
                            var entityParam = listPParameter.FirstOrDefault(o => o.PARANAME == item.ColumnName);
                            if (entityParam != null)
                            {
                                strColumnName = entityParam.PARADESCRIBE;
                            }
                        }
                        if (!string.IsNullOrEmpty(strColumnName))
                        {
                           //item.ColumnName = strColumnName;
                        }
                        else
                        {
                            listDelColumn.Add(item);
                        }
                    }
                }

                //移除
                foreach (var item in listDelColumn)
                {
                    dtResult.Columns.Remove(item);
                }

                dataResult.Result.Result = dtResult;
                //dataResult.Result.Result = GetJsonSource(dtResult);
                dataResult.IsSuccess = true;
                #endregion
            }
            catch (Exception ex)
            {
                LogManager.LogHelper.Error(new LogInfo()
                {
                    ErrorInfo = ex,
                    Tag = ex.StackTrace,
                    Info = "加工记录-获取列表"
                });
                dataResult.IsSuccess = false;
                dataResult.Msg = Resource.SystemException;
            }

            
            return dataResult;
        }
        #endregion

        /// <summary>
        /// 
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public string GetJsonSource(System.Data.DataTable dt)
        {
            string pa = ",";
            try
            {
                StringBuilder returnValue = new StringBuilder("{ \"total\":\" " + dt.Rows.Count.ToString() + "\", \"rows\":[");

                if (dt.Rows.Count > 0)
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        if (i != 0)
                        {
                            returnValue.AppendLine(pa);
                        }

                        string josnItem = "";

                        List<string> itemValue = new List<string>();

                        foreach (DataColumn item in dt.Columns)
                        {
                            object value = dt.Rows[i][item.ColumnName];
                            itemValue.Add(string.Format("\"{0}\":\"{1}\"", item.ColumnName, value != null && value != System.DBNull.Value ? value : string.Empty));

                        }
                        if (itemValue.Count > 0)
                        {
                            josnItem = "{" + string.Join(",", itemValue.ToArray()) + "}";
                        }
                        else
                        {
                            josnItem = string.Empty;
                        }

                        returnValue.AppendLine(josnItem);

                    }

                }
                returnValue.Append("]");


                returnValue.Append("}");

                return returnValue.ToString();
            }
            catch (Exception)
            {

                throw;
            }
        }

        #region 获取加工记录列表Title(WEB根据工序查找设备加工参数)

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="condition">条件</param>
        /// <param name="page">数据页</param>
        /// <returns>数据页</returns>
        public DataResult<DataTable> GetListWithParameterForWebTitle(MainOperation condition)
        {
            DataResult<DataTable> dataResult = new DataResult<DataTable>();
            ProcessParameter conditionPParameter = new ProcessParameter();
            try
            {
                #region 获得加工参数标准值

                //if (!string.IsNullOrEmpty(condition.PROCESSTYPES))
                //{
                //    conditionPParameter.PROCESSTYPES = condition.PROCESSTYPES;
                //}
                //else
                //{
                //    conditionPParameter.PROCESSTYPE = condition.PROCESSTYPE;
                //}

                if (!string.IsNullOrEmpty(condition.WORKCELL_CODE))
                {
                    conditionPParameter.WORKCELL_CODE = condition.WORKCELL_CODE;
                }

                //获取加工参数表中每个工序类别的信息
                var listPParameter = new ProcessParameterDAL().GetList(conditionPParameter);

                #endregion

                if (listPParameter == null || listPParameter.Count == 0)
                {
                    dataResult.Result = new MainOperationDAL().GetListWithOutParameterTitle(condition);
                }

                #region 获得加工记录及加工参数
                else
                {
                    condition.SelectCollumns = String.Join(",", listPParameter.Select(o => o.PARANAME));
                    condition.PARATABLENAME = listPParameter.FirstOrDefault().PARATABLENAME;

                    //获取加工操作与对应加工参数表联合
                    dataResult.Result = new MainOperationDAL().GetListWithParameterTitle(condition);
                }

                if (dataResult.Result == null)
                {
                    dataResult.IsSuccess = false;
                    dataResult.Msg = QMAPP.FJC.Entity.Resource.NothingData;
                    return dataResult;
                }

                DataTable dtResult = dataResult.Result;

                DictManageBLL dictColumnName = new DictManageBLL(DictKind.MAINOPERATIONSEARCHFORM);  
                IList<DataColumn> listDelColumn = new List<DataColumn>(); 

                //设置标题
                foreach (var item in dtResult.Columns.Cast<DataColumn>())
                {
                    if (item.ColumnName == "OPERATEDDATE" || item.ColumnName == "CREATEDATE")
                    {
                        //移除原来datetime类型的OPERATEDDATE、CREATEDATE
                        listDelColumn.Add(item);
                    }
                    else
                    {
                        string nameCode = item.ColumnName;
                        var strColumnName = dictColumnName.GetDictValue(item.ColumnName);
                        if (string.IsNullOrEmpty(strColumnName))
                        {
                            var entityParam = listPParameter.FirstOrDefault(o => o.PARANAME == item.ColumnName);
                            if (entityParam != null)
                            {
                                strColumnName = entityParam.PARADESCRIBE;
                            }
                        }
                        if (!string.IsNullOrEmpty(strColumnName))
                        {
                            item.ColumnName = strColumnName;
                        }
                        else
                        {
                            listDelColumn.Add(item);
                        }
                    }
                }

                //移除
                foreach (var item in listDelColumn)
                {
                    dtResult.Columns.Remove(item);
                }

                dataResult.IsSuccess = true;
                #endregion
            }
            catch (Exception ex)
            {
                LogManager.LogHelper.Error(new LogInfo()
                {
                    ErrorInfo = ex,
                    Tag = ex.StackTrace,
                    Info = "加工记录-获取列表"
                });
                dataResult.IsSuccess = false;
                dataResult.Msg = Resource.SystemException;
            }
            return dataResult;
        }


        /// <summary>
        /// 前台显示字段
        /// </summary>
        /// <param name="condition">工序</param>
        /// <returns></returns>
        public List<ProcessParameter> GetParameterForWebTitle(MainOperation condition)
        {
            //定义返回信息
            List<ProcessParameter> resultList = new List<ProcessParameter>();

            //加载字典表中信息
            DictManageBLL dictColumnName = new DictManageBLL(DictKind.MAINOPERATIONSEARCHFORM);

            DictManageBLL dictColumnSet = new DictManageBLL(DictKind.MAINOPERATIONSEARCHFORMSET);

            try
            {
                //获取参数配置中的加工记录的相关信息
                Dictionary<string, string> dict = dictColumnName.GetModelDictionary(DictKind.MAINOPERATIONSEARCHFORM);

                //将结果结果添加到resultList
                foreach (string key in dict.Keys)
                {

                    List<string> columnSetList = dictColumnSet.GetDictValue(key + "COLUMN").Split(':').ToList<string>();

                    resultList.Add(new ProcessParameter() { PARANAME = key,  PARADESCRIBE = dictColumnName.GetDictValue(key), ALIGNVALUE = columnSetList[0], WIDTH = Convert.ToInt32(columnSetList[1]) });
                }


                //获取将
                ProcessParameter conditionPParameter = new ProcessParameter();

                //if (!string.IsNullOrEmpty(condition.PROCESSTYPES))
                //{
                //    conditionPParameter.PROCESSTYPES = condition.PROCESSTYPES;
                //}
                //else
                //{
                //    conditionPParameter.PROCESSTYPE = condition.PROCESSTYPE;
                //}

                if (!string.IsNullOrEmpty(condition.WORKCELL_CODE))
                {
                    conditionPParameter.WORKCELL_CODE = condition.WORKCELL_CODE;
                }

                //获取加工参数表中每个工序类别的信息
                if (!string.IsNullOrEmpty(condition.WORKCELL_CODE))
                //if (!string.IsNullOrEmpty(condition.PROCESSTYPE))
                {
                    var listPParameter = new ProcessParameterDAL().GetList(conditionPParameter);

                    listPParameter = listPParameter.OrderBy(o => o.SHOWINDEX).ToList<ProcessParameter>();

                    foreach (var para in listPParameter)
                    {
                        resultList.Add(
                            new ProcessParameter()
                            {
                                PARANAME = para.PARANAME,
                                PARADESCRIBE = para.PARADESCRIBE,
                                WIDTH = para.WIDTH,
                                ALIGNVALUE = para.ALIGNVALUE,
                                SHOWINDEX = para.SHOWINDEX
                            });
                    }
                }
                return resultList;
            }
            catch (Exception ex)
            {

                LogManager.LogHelper.Error(new LogInfo()
                {
                    ErrorInfo = ex,
                    Tag = ex.StackTrace,
                    Info = "加载动态列失败!"
                });
                return resultList;
            }
           
        }

        #endregion 

        #region 统计
        /// <summary>
        /// 产量趋势统计
        /// </summary>
        /// <param name="condition"></param>
        /// <returns></returns>
        public  DataResult<List<MainOperation>> GetListGroupBy(MainOperation condition)
        {
            DataResult<List<MainOperation>> result = new DataResult<List<MainOperation>>();
            try
            {
                 result.Result  = new MainOperationDAL().GetListGroupBy(condition);

            }
            catch (Exception ex)
            {
                LogManager.LogHelper.Error(new LogInfo()
                {
                    ErrorInfo = ex,
                    Tag = ex.StackTrace,
                    Info = "产量趋势统计-获取列表(产量趋势统计)!"
                });
                result.IsSuccess = false;
                result.Msg = Resource.SystemException;
                throw ex;
            }
            result.IsSuccess = true;
            return result;
        }

         /// <summary>
        /// 合格率
        /// </summary>
        /// <param name="condition"></param>
        /// <returns></returns>
        public  DataResult<List<MainOperation>> GetListGroupByStauts(MainOperation condition)
        {
            DataResult<List<MainOperation>> result = new DataResult<List<MainOperation>>();
            try
            {
                 result.Result  = new MainOperationDAL().GetListGroupByStauts(condition);

            }
            catch (Exception ex)
            {
                LogManager.LogHelper.Error(new LogInfo()
                {
                    ErrorInfo = ex,
                    Tag = ex.StackTrace,
                    Info = "合格率-获取列表(合格率统计)!"
                });
                result.IsSuccess = false;
                result.Msg = Resource.SystemException;
                throw ex;
            }
            result.IsSuccess = true;
            return result;
        }
        #endregion


        #region 产品返修

        public DataResult MendProudct(MainOperation condition)
        {

            DataResult result = new DataResult();
            MainOperationDAL modal = new MainOperationDAL();
            MainOperation mo = modal.Get(condition);

            ProductDAL prodal = new ProductDAL();

            Product entity = prodal.Get(new Product() { PID = mo.PDID });

            //判断状态是否正确
            if (entity.STATUS != EnumGeter.STATUS.SCRAP.GetHashCode().ToString())
            {
                result.IsSuccess = false;

                result.Msg = "该表皮为正常件!";

                return result;
            }

            entity.STATUS = EnumGeter.STATUS.QUALIFIED.GetHashCode().ToString();
            mo.PRODUCTCODESTR = "是";

            using (IDataSession session = AppDataFactory.CreateMainSession())
            {
                session.OpenTs();
                prodal.BaseSession = session;
                modal.BaseSession = session;

                prodal.Update(entity);
                modal.Update(mo);

                session.CommitTs();

            }

            result.IsSuccess = true;
            result.Msg = "返修完成!";
            return result;

        }

        #endregion

        public DataResult<DataTable>  GetExportData(MainOperation condition)
        {

            DataResult<DataTable> dataResult = new DataResult<DataTable>();
            dataResult.IsSuccess = true;
            try
            {
                #region 获得加工参数标准值
                var conditionPParameter = new ProcessParameter
                {
                    WORKCELL_CODE = condition.WORKCELL_CODE,
                };

                var listPParameter = new ProcessParameterDAL().GetList(conditionPParameter);


                if (listPParameter == null || listPParameter.Count == 0 || string.IsNullOrEmpty( condition.WORKCELL_CODE))
                {
                    dataResult.Result = new MainOperationDAL().GetListWithOutParameterDt(condition);
                }
                #endregion

                #region 获得加工记录及加工参数
                else
                {
                    condition.SelectCollumns = String.Join(",", listPParameter.Select(o => o.PARANAME));
                    condition.PARATABLENAME = listPParameter.FirstOrDefault().PARATABLENAME;
                    dataResult.Result = new MainOperationDAL().GetListWithParameterDt(condition);
                }

                if (dataResult.Result == null)
                {
                    dataResult.IsSuccess = false;
                    dataResult.Msg = QMAPP.FJC.Entity.Resource.NothingData;
                    dataResult.Result = new DataTable();
                    return dataResult;
                }

                DataTable dtResult = dataResult.Result as DataTable;

                //DictManageBLL dictColumnName = new DictManageBLL(DictKind.MAINOPERATIONSEARCHFORM);
                //DictManageBLL dictProcessType = new DictManageBLL(DictKind.PROCESSTYPE);
                //DictManageBLL dictProductType = new DictManageBLL(DictKind.PRODUCTTYPE);
                //DictManageBLL dictLJStatus = new DictManageBLL(DictKind.LJSTATUS);
                //DictManageBLL dictOperateState = new DictManageBLL(DictKind.OPERATESTATE);
                //DictManageBLL dictPSStatus = new DictManageBLL(DictKind.PRODUCTSTATUS);

                //IList<DataColumn> listDelColumn = new List<DataColumn>();

                //转换枚举描述
                //foreach (DataRow item in dtResult.Rows)
                //{
                //    item["PROCESSTYPE"] = dictProcessType.GetDictValue(item["PROCESSTYPE"].ToString());
                //    item["PRODUCTTYPE"] = dictProductType.GetDictValue(item["PRODUCTTYPE"].ToString());
                    //item["STATUS"] = dictPSStatus.GetDictValue(item["STATUS"].ToString());
                    //item["OPERATESTATE"] = dictOperateState.GetDictValue(item["OPERATESTATE"].ToString());
                //    //因为日期类型转成json绑定到页面显示格式错误,所以在datatable加上两个字符串型的操作时间和加工完成时间用于显示在页面上
                //    if (!string.IsNullOrEmpty(item["OPERATEDDATESTR"].ToString()))
                //    {
                //        item["OPERATEDDATE"] = (Convert.ToDateTime(item["OPERATEDDATESTR"].ToString())).ToString("yyyy-MM-dd HH:mm:ss").Replace('/', '-');
                //    }
                //    if (!string.IsNullOrEmpty(item["CREATEDATESTR"].ToString()))
                //    {
                //        item["CREATEDATE"] = ((DateTime)item["CREATEDATESTR"]).ToString("yyyy-MM-dd HH:mm:ss");
                //    }
                //}

                ////设置标题
                //foreach (var item in dtResult.Columns.Cast<DataColumn>())
                //{
                //    if (item.ColumnName == "OPERATEDDATE" || item.ColumnName == "CREATEDATE")
                //    {
                //        //移除原来datetime类型的OPERATEDDATE、CREATEDATE
                //        //listDelColumn.Add(item);
                //    }
                //    else
                //    {
                //        var strColumnName = dictColumnName.GetDictValue(item.ColumnName);
                //        if (string.IsNullOrEmpty(strColumnName))
                //        {
                //            var entityParam = listPParameter.FirstOrDefault(o => o.PARANAME == item.ColumnName);
                //            if (entityParam != null)
                //            {
                //                strColumnName = entityParam.PARADESCRIBE;
                //            }
                //        }
                //        if (!string.IsNullOrEmpty(strColumnName))
                //        {
                //            //item.ColumnName = strColumnName;
                //        }
                //        else
                //        {
                //            listDelColumn.Add(item);
                //        }
                //    }
                //}

                ////移除
                //foreach (var item in listDelColumn)
                //{
                //    dtResult.Columns.Remove(item);
                //}

                dataResult.Result = dtResult;
                //dataResult.Result.Result = GetJsonSource(dtResult);
                dataResult.IsSuccess = true;
                #endregion
            }
            catch (Exception ex)
            {
                LogManager.LogHelper.Error(new LogInfo()
                {
                    ErrorInfo = ex,
                    Tag = ex.StackTrace,
                    Info = "加工记录-获取列表"
                });
                dataResult.IsSuccess = false;
                dataResult.Msg = Resource.SystemException;
            }


            return dataResult;

            //return new DataResult<DataTable>();
        }


        #region 加工操作(总成打印条码)成都 临时打印
        /// <summary>
        /// 加工操作(总成打印条码)
        /// 20181104gzf
        /// </summary>
        /// <param name="barcode"></param>
        /// <returns></returns>
        public DataResult<Main> GetFinalPrintCode(string material)
        {

            DataResult<Main> result = new DataResult<Main>();
            Main main = new Main();


            PrintCode condition = new MainDAL().GetFinalMaxMainCodePrint(material);

            //string mainCode = (Convert.ToInt32(condition.MAINCODE) + 1) + "";

            main.MAINCODE = condition.MAINCODE;
            //main.MAINCODE = "052 8KY" + mainCode.PadLeft(7, '0');
            //main.MAINCODE = new FileCopyRecordDAL().GetBarcode(main.MAINCODE);
            main.publicCode = condition.COLOR_CODE;

            //PrintCode pc = new PrintCode();
            //pc.PID = condition.PID;
            //pc.MAINCODE = main.MAINCODE;
            //pc.ISCOMPLETE = 0;
            //pc.PRODUCTCODE = condition.PRODUCTCODE;
            //pc.CREATETIME = System.DateTime.Now;

            //PrintCodeDAL dal = new PrintCodeDAL();
            //dal.Insert(pc);
            result.Result = main;
            return result;

        }
        #endregion

    }

}