/// 
///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;
             }
             isProcessing = true;
             System.Diagnostics.Debug.WriteLine("begin make new wave .....{0}", DateTime.Now);
             DataTable dt = _obj.getNewPickList().Tables[0];
             if (dt.Rows.Count == 0)
             {
                 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)
                 {
                     continue;
                 }
                 //if (string.IsNullOrEmpty(lastPickorder))
               //  {
               //      lastPickorder = wop.pickOrderNo;
               //  }
                 if (!lastPickorder.Equals( wop.pickOrderNo))
                 {
                     lastPickorder = wop.pickOrderNo;
                     color++;
                     if (color > maxColorCnt )
                     {
                         break;
                     }
                 }
                 if (i >= pickDetailMaxInWave)
                 {
                     break;
                 }
                               
                 i++;
                              
                // lstPort = new List();
                  
              //   tmplabelCnt.Clear();
              //   tmpcomCnt.Clear();
              
                 //DateTime d11 = DateTime.Now;
                 //System.Diagnostics.Debug.WriteLine(string.Format("    开始检查是否超限 --- {0}", d11));
                
                     
#if DEBUG  
                 
                 int id = new Random().Next(1,lblist.Count);
                 Thread.Sleep(10);
                 int lastId = 0;
                     wop.elabId = lblist[id]; //new Random().Next(minId, maxId + 1); //测试。。。随机分配标签id 为 1-3
                     while (lblist.Count > 1 && lastId == wop.elabId)
                     {
                         id = new Random().Next(1, lblist.Count);
                         wop.elabId = lblist[id];
                     }
                     lastId = wop.elabId;
                     if (wop.elabAddress == 0)
                     {
                         wop.elabAddress = new Random().Next(11,33); 
                     }
#endif
 
                 string lbAdrss = wop.elabId + "-" + wop.elabAddress;
                 if (labelAddress.Contains(lbAdrss))
                 {
                     continue;
                 }
                 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;
                
                     wpl = new WmsOutPickLable_tmp(); 
                     wpl.color = color; 
                     wpl.count = wop.count;
                     wpl.locationId = wop.locationId;
                     wpl.elabAddress = wop .elabAddress;
                     wpl.elabId = wop.elabId;
                     // wpl.elabId = new Random().Next(1,4); //测试。。。随机分配标签id 为 1-3
                     wpl.port = wop.port;
                     wpl.pickOrderNo = wop.pickOrderNo;
#if DEBUG
                     try
                     {
                         wpl.port = comLables[wpl.elabId];  //wop.elabId < 4 ?5 :3; //测试。。。 分配标签端口为3
                     }
                     catch { }
#endif
                     wpl.waveOrder = waveOrder;
                     wpl.operater = this.operId;
                     lstLabel_tmp.Add(wpl);
                     wop.waveOrder = waveOrder;
                     
                     lstLabel.Add(wop);
                 //保存整货和零货出库分拣数据 
             }
             try
             {
               //  using (TransactionScope scope1 = new TransactionScope())
                 {
                     foreach (WmsOutPickLable_tmp wp in lstLabel_tmp)  //建立电子拣选临时数据
                     {
                         wp.Add();
                     }
                     foreach (WmsOutPickLable  wp in lstLabel )  //建立电子拣选临时数据
                     {
                         wp.Update();
                     }
                  //   scope1.Complete();
                     //TimeSpan ts2 = DateTime.Now - d12;
                     //System.Diagnostics.Debug.WriteLine(string.Format("   {1}  保存完毕 {0}  cost {2} .....", request.pickOrderNo, DateTime.Now, ts2.TotalSeconds + " : " + ts2.TotalMilliseconds));
                 }
                 waveSize++;
                 //System.Diagnostics.Debug.WriteLine(string.Format("{1}  处理完毕 {0}  cost {2} .....", request.pickOrderNo,DateTime.Now, ts.TotalSeconds +" : "+ ts.TotalMilliseconds));
             }
             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();
             ////通知整库出货
             //Thread light = new Thread(lightLables);
             //light.IsBackground = true;
             //light.Start();
             //  lightLables();
             WmsConstants.WAVE_CURRENT_ORDER = waveOrder;
             WmsConstants.WAVE_LAST_TIME = DateTime.Now;
             isProcessing = false;
             //点亮标签开始捡货 
          //   elelab.pick.send_data_pick(_obj.getData4Pick(waveOrder).Tables[0], enumLabelPickType.pick);
           
             isProcessing = false;
 
         }
         internal void finishCurrentWave(string waveNo,bool isForce)
         {
             {
                 //string waveOrder = pickLabelDetail.finishCurrentPickingData();//结束当前拣选的数据
                 // if (!string.IsNullOrEmpty(waveOrder))
                 // {
                 try
                 {
                     if (isForce)
                     {
                         //TODO: to turn off the lights
                     }
                     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 = "";
                         }
                        scope.Complete();
                     }
                     //  _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;
                 }
             }
             // } 
             
         }
    }
    
    
}