/// 
///LOGIC CLASS FOR TABLE t_wmsOutPickLable
///By wm with codesmith. 
///on 05/22/2017
/// 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DeiNiu.wms.Data.Model;
using System.Data;
using System.Transactions;
using DeiNiu.Data.BaseObject;
using DeiNiu.Utils;
using System.Threading;
namespace DeiNiu.wms.Logical
{
    [Serializable]
    public class lWmsOutPickLable   :lbase
    {
        WmsOutPickLable _obj;
        
        public lWmsOutPickLable()
        {
             initialize();
        }
 
        public  WmsOutPickLable getWmsOutPickLable
        {
            get
            {
                return _obj;
            }
        }
        protected override BaseModel getModel()
        {
            return _obj;
        }
  
		/// 
		/// get all data
		/// 
        public DataSet getAllData()
        {
           return _obj.Query();
        }
        /// 
        /// get all data
        /// 
        public DataSet getAllActiveData()
        {
            return _obj.QueryActived();
        }
		/// 
		/// get a record by id
		/// 
        public void initialize(int id)
		{
            _obj = id != 0 ? new WmsOutPickLable(id) : new WmsOutPickLable();
		}
        /// 
		/// get a record by id 0
		/// 
        public void initialize()
        {
            initialize(0);
        }
         /// 
        /// get a record by id
        /// 
        public void initialize(DataRow dr)
        {
            _obj =   new WmsOutPickLable(dr);
        }
        
 
 
        //begin cust db operation, query, excute sql etc.
        
     
        /// 
        /// update in a transaction scrop
        /// 
        public void update()
        {
            if (valid())
            { 
                    _obj.Update(); 
            }
        }
        
         private bool valid()
        {
            return true;
        }
         //static Dictionary> comLables = new Dictionary>();
         static List lblist = new List();
         static Dictionary comLables = new Dictionary();
         void initialDebugSetting()
         {
              
                 try
                 {
                     string labels = "1,2,3,4,5,6,7,8,9,10,11,12";
                     string[] lbs = labels.Split(',');
                     foreach (string s in lbs)
                     {
                         comLables[Convert.ToInt16(s.Trim())] =6;
                         lblist.Add(Convert.ToInt16(s.Trim()));
                     }
                 }
                 catch
                 {
                     
                 }
 
         }
         private string waveOrder;
         static bool isProcessing = false;
        
         //   public static bool isProcessWaveing = false;
         /// 
         /// 开始新波次
         /// 
         /// 
         public void newPickWave()
         {
             if (isProcessing)
             {
                 return;
             }
             try
             {
                 isProcessing = true;
                 doWaveProcess();
             }
             catch (Exception er)
             {
             }
             isProcessing = false;
         }
         public void doWaveProcess()
         { 
             System.Diagnostics.Debug.WriteLine("begin make new wave .....{0}", DateTime.Now);
             DataTable dt = _obj.getNewPickList().Tables[0];
             if (dt.Rows.Count == 0)
             {
                 _obj.updateWaveStatus();
                 return;
             }
#if DEBUG
             // if (lblist.Count == 0)
             {
                 lblist.Clear();
                 initialDebugSetting();
             }
             lblist.Sort();
             int minId = lblist[0];
             int maxId = lblist[lblist.Count - 1];
#endif
             // List strecs = null;
            // waveOrder = Util.getOrderNo(enumCreateOrderType.waveOrder, _obj.getNextSeq());
             int labelMaxInWave = WmsConstants.MAX_LABEL_DATA_IN_A_WAVE; //一个标签一个波次只能存储40条数据
             int pickDetailMaxInWave = WmsConstants.MAX_CONTROL_DATA_IN_A_WAVE;  //一个控制器最大存储1200条
             Dictionary labelCnt = new Dictionary();
             Dictionary comCnt = new Dictionary();
            // List labelAddress = new List();
             Dictionary tmplabelCnt = new Dictionary();
             Dictionary tmpcomCnt = new Dictionary();
             bool isReachLimit = false;
             int waveSize = 0;
           //  List lstPort;
             List lstLabel_tmp = new List();
             List lstLabel  = new List();   
             
             int i = 0;
                         
             //开始处理有零货的订单
             DateTime d0 = DateTime.Now;
             double totoalTime = 0d;
             int maxColorCnt = WmsConstants.MAX_COLORS;
             int color = 0;
             string lastPickorder = "";
             foreach (DataRow dr in dt.Rows )
             {
                 DateTime d00 = DateTime.Now;
                 WmsOutPickLable wop = new WmsOutPickLable(dr);
                 if (
                    // wop.waveOrder.Length > 0 
                   //  || 
                     wop.count<=0
                     || wop.state>0
                     )
                 {
                     continue;
                 }
 
                 if (i >= pickDetailMaxInWave)
                 {
                     break;
                 }
                               
                 i++;
             
                // string lbAdrss = wop.elabId + "-" + wop.elabAddress;
               
                // labelAddress.Add(lbAdrss);
                     if (labelCnt.ContainsKey(wop.elabId))
                     {
                         if (labelCnt[wop.elabId] <= labelMaxInWave)
                         {
                             labelCnt[wop.elabId]++;
                         }
                         else
                         {
                             continue;
                         }
                          
                     }
                     else
                     {
                         labelCnt[wop.elabId] = 1;
                     }
                     if (comCnt.ContainsKey(wop.port))
                     {
                         //comCnt[wop.port] = comCnt[wop.port] + 1;
                         if (comCnt[wop.port] <= pickDetailMaxInWave)
                         {
                             comCnt[wop.port]++;
                         }
                         else
                         {
                             continue;
                         }
                     }
                     else
                     { 
                         comCnt[wop.port] = 1;
                     }
                  
                 //TimeSpan ts11 = DateTime.Now - d11;
                 //System.Diagnostics.Debug.WriteLine(string.Format("    检查是否超限完毕 --- cost {0}", ts11.TotalSeconds + " : " + ts11.TotalMilliseconds));
                 if (isReachLimit)
                 {
                     isReachLimit = false;
                     System.Diagnostics.Debug.WriteLine(string.Format("超过限制,继续下条数据.... "));
                     continue;
                 }
                  
                     WmsOutPickLable_tmp wpl = new WmsOutPickLable_tmp(dr);
                     if (i == 998)
                     {
                         i++;
                         i--;
                     }
                    
                     lstLabel_tmp.Add(wpl);
                     if (String.IsNullOrEmpty(wop.waveOrder))
                     {
                         wop.waveOrder = waveOrder;
                         wpl.waveOrder = waveOrder;
                        
                     }
                     else
                     {
                         waveOrder = wop.waveOrder;
                     }
                     lstLabel.Add(wop);
                 
                    // lstLabel_tmp.Add(wpl);
                 //保存整货和零货出库分拣数据 
             }
             try
             {
                 using (TransactionScope scope1 = new TransactionScope())
                 {
                     foreach (WmsOutPickLable_tmp wp in lstLabel_tmp)  //建立电子拣选临时数据
                     {
                         wp.color = Utils.Util.getColor(wp.color);
                         wp.Add();
                     }
                     foreach (WmsOutPickLable  wp in lstLabel )  //建立电子拣选临时数据
                     {
                         wp.pickOrderNo = "";
                         wp.Update();
                     }
                  
                     scope1.Complete();
                 }
                 waveSize++;
            }
             catch (Exception e)
             {
                 System.Diagnostics.Debug.WriteLine(e.Message);
             }
             TimeSpan ts1 = DateTime.Now - d0;
             System.Diagnostics.Debug.WriteLine(string.Format("{0} 零库处理完毕-----  cost {1} .....{2}", DateTime.Now, ts1.TotalSeconds + " : " + ts1.TotalMilliseconds, totoalTime));
             // insert tmp data for validation
            
             WmsConstants.WAVE_CURRENT_PICK_STATUS.Clear(); 
             WmsConstants.WAVE_CURRENT_ORDER = waveOrder;
             WmsConstants.WAVE_LAST_TIME = DateTime.Now;
             _obj.updateWaveStatus();
        
         }
         internal void finishCurrentWave(string waveNo,bool isForce)
         {     
            try
              { 
                     using (TransactionScope scope = new TransactionScope())
                     {
                         _obj.finishCurrentPickingData(waveNo,isForce);//结束当前拣选的数据
                         if (!WmsConstants.WAVE_CURRENT_ORDER.Equals(WmsConstants.WAVE_LAST_ORDER))
                         {
                             WmsConstants.WAVE_LAST_ORDER = WmsConstants.WAVE_CURRENT_ORDER;
                             TimeSpan ts = DateTime.Now - WmsConstants.WAVE_LAST_TIME;
                             WmsConstants.WAVE_TOTAL_SECONDS += ts.Seconds;
                             WmsConstants.WAVE_CNT++;
                             //WmsConstants.WAVE_CURRENT_ORDER = "";
                             WmsConstants.WAVE_SECONDS = WmsConstants.WAVE_TOTAL_SECONDS / WmsConstants.WAVE_CNT;
                         }
                         if (!string.IsNullOrEmpty(WmsConstants.WAVE_CURRENT_ORDER))
                         {
                             WmsConstants.WAVE_CURRENT_ORDER = "";
                         }
                        _obj.updateWaveStatus();
                        scope.Complete();
                        WmsConstants.WAVE_LAST_END = DateTime.Now;
                     }
                     //  _canNewWave = true;
                     // TaskCallBack(); //send info to the main ui to start new wave.,for its in another thread, will neve success.
                 }
                 catch (Exception er)
                 {
                    // LogHelper.WriteLog(typeof(lWmsOutPickRequest), er);
                    // finishCurrentWave(waveNo,isForce);
                      throw er;
                 }
            
             
         }
         public void updateWaveFlag()
         {
             _obj.updateWaveStatus();
         }
    }
    
    
}