using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Windows.Forms;
using DevExpress.XtraBars;
using DevExpress.XtraGrid.Views.Base;
//using DeiNiu.wms.Logical;
using DeiNiu.wms.Data;
using DevExpress.XtraGrid.Columns;
 
using System.Threading;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraEditors.DXErrorProvider;
using DeiNiu.wms.Data.Model;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DeiNiu.Utils;
using DeiNiu.wms.win.utils.print;
//using DeiNiu.wms.win.ServiceReferenceInRequest; 
//using DeiNiu.wms.win.ServiceReferenceInRequestLocal;
using DeiNiu.wms.win.ServiceReferenceLot;
namespace DeiNiu.wms.win
{
    public partial class LotSetup : BasicRibbonForm
    {
      
        printIn reportPrint = new printIn() ;
      //  lWmsStock ls = new lWmsStock();
      //  lWmsInRequest lgt = new lWmsInRequest();
        private string fieldName = WmsLocation.fields.locationId.ToString();
        private string fieldGoodType = WmsLocation.fields.whGoodsType.ToString();
        private string lastQuery = "";
        private DataTable dt;
        private DataTable dtAtt;
      //  DataTable dtIndetail;
        private int selectedRowIndex = -1;
 
        WcfLot currentLot;
        WcfLotAtt currentAtt;
        private bool isShowingInRequest = true;
        public LotSetup()
        {
         
            InitializeComponent(); 
          
            initialControls();
            
            //    loadData();
            
        }
        #region initialControls
        private void initialControls()
        {
            initialComboBoxes();
            initialPagerControls();
            initialDataGrid();
            initialQueryInput(); 
            setValidationRule();
            layoutControlItem2.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
            layoutControlItem14.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
#if DEBUG
            layoutControlItem2.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
            layoutControlItem14.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
             
#endif     
        }
        private void initialComboBoxes()
        {
            initialComboBoxs(comAttType, enLotAttType,false);
        }
      
        private void setValidationRule()
        {
          //  dxValidationProvider.SetValidationRule(comWarehouse, ValidationRules.notEmptyValidationRule);
            //txtGoodType.Properties.MaxLength = 40;
            //txtGoodDesc.Properties.MaxLength = 250;
            //textEdit1.Properties.MaxLength = txtGoodType.Properties.MaxLength;
        }
        private void initialQueryInput()
        {
        }
      
        private void initialDataGridColumns(GridView gridView)
        {
            setupGridView(gridView, false);
            //setupGridView(gridView2, false,false);
            //setupGridView(gridView3, false,false);
            //   gridviewGoodsType.PopulateColumns();
            gridView.Columns.Clear();
            // gridviewGoodsType.Columns.Remove(gridviewGoodsType.Columns["DealerPrice"]); 
            GridColumn myCol0 = new GridColumn() { Caption = "ID", Visible = true, FieldName = "id" };
            myCol0.Visible = false;
            gridView.Columns.Add(myCol0);
            if (gridView == gridView1)
            {
                GridColumn myCol1 = new GridColumn() { Caption = "批次名称", Visible = true, FieldName = Lot.fields.lotName.ToString() };
                GridColumn myCol2 = new GridColumn() { Caption = "批次描述", Visible = true, FieldName = Lot.fields.description.ToString() };
                GridColumn myCol3 = new GridColumn() { Caption = "创建人", Visible = true, FieldName = Lot.fields.operater.ToString() };
                GridColumn myCol4 = new GridColumn() { Caption = "创建日期", Visible = true, FieldName = "createtime" };
               
                gridView.Columns.Add(myCol1);
                gridView.Columns.Add(myCol2);
                gridView1.Columns.Add(myCol3);
                gridView.Columns.Add(myCol4);
                
            }
            
         //   this.gridView1.Columns.Add(myCol4);
        
           
            //to show bottom scroll bar
            gridView.OptionsView.ColumnAutoWidth = false;
            gridView.BestFitColumns();
           // gridView.Focus();
            //if (gridView1 == gridView)
            //{
            //    this.gridView1.Focus(); ;
            //}
        //    initialGridView2Columns();
        //    gridControl2.DataSource = null;
        }
        private void initialGridView2Columns(GridView gridview)
        {
            setupGridView(gridview, false, true, false);
            gridview.FocusRectStyle = DrawFocusRectStyle.None;
            //   gridviewGoodsType.PopulateColumns();
            gridview.Columns.Clear();
            // gridviewGoodsType.Columns.Remove(gridviewGoodsType.Columns["DealerPrice"]); 
            GridColumn myCol0 = new GridColumn() { Caption = "ID", Visible = true, FieldName = "id" };
            myCol0.Visible = false;
            gridview.Columns.Add(myCol0);
            GridColumn myCol1 = new GridColumn() { Caption = "属性名称", Visible = true, FieldName = LotAtt.fields.attName.ToString() };
            GridColumn myCol2 = new GridColumn() { Caption = "属性类型", Visible = true, FieldName = LotAtt.fields.attType.ToString() };
            GridColumn myCol3 = new GridColumn() { Caption = "列表", Visible = true, FieldName = LotAtt.fields.isList.ToString() };
            GridColumn myCol4 = new GridColumn() { Caption = "列表FLAG", Visible = true, FieldName = LotAtt.fields.listId.ToString() };
            GridColumn myCol5 = new GridColumn() { Caption = "创建人", Visible = true, FieldName = LotAtt.fields.operater.ToString() };
            GridColumn myCol6 = new GridColumn() { Caption = "创建时间", Visible = true, FieldName = "createtime" };
            GridColumn myCol7 = new GridColumn() { Caption = "可选项", Visible = true, FieldName = LotAtt.fields.isOptional.ToString() };
            if (gridview == gridView2)
            {
                gridview.Columns.Add(myCol1);
                gridview.Columns.Add(myCol2);
                gridview.Columns.Add(myCol3);
                gridview.Columns.Add(myCol4);
                gridview.Columns.Add(myCol5);
                gridview.Columns.Add(myCol7);
                gridview.Columns.Add(myCol6);
     
            }
             
           
            //to show bottom scroll bar
            gridview.OptionsView.ColumnAutoWidth = false;
            gridview.BestFitColumns();
          //  gridView2.Focus();
        }
        
        #endregion
        private void initialRequestOrders()
        {
            showWaitForm();
            try{
                //lotClient.getInRequests();
               // getInValidOrders();
            }
            //catch (DeiNiuTimeOutException te)
            //{
            //     
            //}
            catch(Exception e){
                showErrorMsg(e.Message);
                }
            finally{
                closeWaitForm();
            }
          
        }
      
        ///   
        /// loading data
        ///   
        private int loadData()
        {
            
            //this.gridviewGoodsType.DataSource = lgt.GetAllActiveData().Tables[0].DefaultView;
            showWaitForm();
           
            try
            {
                // this.splashScreenManager1.ShowWaitForm();
               string query = (this.txtOrderNo.Text.Trim().Length == 0 ? "" : string.Format("{0} =#'{1}';", "lotName", filtRiskChar(txtOrderNo.Text.Trim())))
                   ;
                bool isQueryNotChanged = lastQuery.Equals(query);
                this.pager1.PageCurrent = isQueryNotChanged ? this.pager1.PageCurrent : 1; //根据查询条件的变化给pager赋值
                int start = (pager1.PageSize * (pager1.PageCurrent - 1) + 1);
                int end = (pager1.PageSize * pager1.PageCurrent);
                lastQuery = query;
                DataSet ds = lotClient.queryLots(query, start, end);// lgt.Query(query, start, end);
                closeClient();;
                dt = ds.Tables[0];
                int cnt = Convert.ToInt32(ds.Tables[1].Rows[0][0].ToString());
                //dt = lgt.Query(query, start, end); //string.IsNullOrEmpty(query) ? lgt.GetGoodType.getAllData(start, end) : lgt.g;
                dt.PrimaryKey = new DataColumn[] { dt.Columns["ID"] };
                bool firstLoad = !isQueryNotChanged || this.gridControl1.DataSource == null;
                this.gridControl1.DataSource = dt.DefaultView;
                initialDataGridColumns(gridView1);
                //update selected row index to the last updated one.
               
                if (currentLot !=null)
                {
                    selectedRowIndex = -1;
                    DataRow dr = dt.Rows.Find(currentLot.ID);
                    if (dr != null)
                    {
                        selectedRowIndex = dt.Rows.IndexOf(dr);
                    }
                    if (selectedRowIndex >= 0 && dt.Rows.Count > selectedRowIndex)
                    {
                        // gridView1.SelectRow(selectedRowIndex);
                        gridView1.FocusedRowHandle = selectedRowIndex;
                        //  gridView1.MakeRowVisible(selectedRowIndex);
                    }
                    //gridView1.FocusedRowHandle = selectedRowIndex;
                }else
               // if (firstLoad)
                {
                    selectedRowIndex = 0;
                    gridView1.FocusedRowHandle = 0;
                    gridView1.SelectRow(0);
                    
                }
                setCurrentRequestDetail();
                closeWaitForm();
                return cnt;
            }
            catch (Exception e)
            {
                showErrorMsg(e,e.Message);
            }
            closeWaitForm();
            return 0;// lgt.getRowCount(query);
            // return lgt.GetGoodType.QueryCount(); 
        }
         
        private void bindDetail()
        {
        }
        private void setDataBack()
        {
        }
        private bool validData()
        {
            bool isvalid = dxValidationProvider1.Validate();
            // MessageBox.Show("goodtype is " + txtGoodType.Text +", is valid ? " + isvalid);
            return isvalid;
            //String gdtype = txtGoodType.Text.Trim();
            //if (gdtype.Length == 0)
            //{
            //    dxValidationProvider.Validate();
            //    return false;
            //} 
            //return true;
        }
         
       
        ///   
        /// 分页控件产生的事件  
        ///   
        private int pager_EventPaging(DeiNiu.Controls.pager.EventPagingArg e)
        {
            selectedRowIndex = -1; //reset currentRowIndex
            return loadData();
        }
        private void initialPagerControls()
        {
            pager1.MaximumSize = new Size(0, 20);
            pager1.EventPaging += new DeiNiu.Controls.pager.EventPagingHandler(pager_EventPaging);
            #region DataGridView与Pager控件绑定
            this.pager1.PageCurrent = 1;//当前页为第一页  
            pager1.PageSize = Utils.WmsConstants.PAGER_SIZE;//每页行数  
            this.pager1.Bind();//绑定  
            #endregion
        }
        bool isCheckedIn = false;
        private void gridView1_FocusedRowObjectChanged(object sender, FocusedRowObjectChangedEventArgs e)
        {
            if (gridView1.FocusedRowHandle < 0 || gridView1.FocusedRowHandle == selectedRowIndex || gridView1.FocusedRowHandle==0 && isCheckedIn)
            {
                isCheckedIn = gridView1.FocusedRowHandle > 0;
                if (gridView1.IsGroupRow(e.RowHandle)) //set first row of group selected
                {
                    selectedRowIndex = gridView1.GetChildRowHandle(e.RowHandle, 0);
                    setCurrentRequestDetail();
                }
                if (isCheckedIn)
                {
                    isCheckedIn = false;
                }
                    return;
                
            }
            selectedRowIndex = gridView1.FocusedRowHandle;
            // showErrorMsg("selection:"+ selectedRowIndex);
            setCurrentRequestDetail();
            
        }
        private void clearInputs()
        {
        }
        
        private void gridView1_DataSourceChanged(object sender, EventArgs e)
        {
            if (selectedRowIndex >= 0 && dt.Rows.Count > selectedRowIndex)
            {
                gridView1.FocusedRowHandle = selectedRowIndex;
                gridView1.MakeRowVisible(selectedRowIndex);
            }
        }
       
        //to show in detail
        int selectedAttIndex = -1;
        string AttName;
        int selectedAttId;
        int selectedAttDetailId = -1;
        WcfLotAtt currentDetail = null;
        private void gridView2_FocusedRowObjectChanged(object sender, FocusedRowObjectChangedEventArgs e)
        {
            if (!isShowingInRequest)
            {
                return;
            }
            if (gridView2.FocusedRowHandle < 0 || gridView2.FocusedRowHandle == selectedAttIndex)
            {
                if (gridView2.IsGroupRow(e.RowHandle)) //set first row of group selected
                {
                    selectedAttIndex = gridView2.GetChildRowHandle(e.RowHandle, 0);
                    setCurrentInDetail();
                }
                return;
            }
            selectedAttIndex = gridView2.FocusedRowHandle;
            // showErrorMsg("selection:"+ selectedRowIndex);
            setCurrentInDetail();
        }
        private void gridView2_DataSourceChanged(object sender, EventArgs e)
        {
            if (!isShowingInRequest)
            {
                return;
            }
            if (selectedAttIndex >= 0)// && dtIndetail.Rows.Count > selectedInIndex)
            {
                gridView2.FocusedRowHandle = selectedAttIndex;
                gridView2.MakeRowVisible(selectedAttIndex);
            }
        }
        private bool getCurrentAttObject()
        {/*
            if (!isShowingInRequest)
            {
                return false;
            }
            */
            if (selectedAttIndex < 0)// || selectedInIndex >= dtIndetail.Rows.Count)
            {
                return false;
            }
            //  DataRow currentRow = dt.Rows[selectedRowIndex];
            DataRowView dr = (DataRowView)(GetGridViewFilteredAndSortedData(gridView2)[selectedAttIndex]);
            AttName = dr["attName"].ToString();
            selectedAttId = Convert.ToInt32(dr["id"].ToString());
            currentDetail = getWcfObject( new LotAtt(dr.Row));
            return true;
        }
        private void setCurrentInDetail()
        {
           
            if (!getCurrentAttObject() || string.IsNullOrEmpty( AttName))
            {
                return;
            }
            /// gridView1.FocusedRowHandle = selectedRowIndex;//
            //  gridView1.SelectRow(selectedRowIndex);
            showWaitForm();
            try
            {
               
                txtAttributeName.Text = currentDetail.attName;
                this.chkStock.Checked= currentDetail.isOptional;
                this.txtAttListId.Text = currentDetail.listId + "";
                btnDel.Enabled = btnUpdate.Enabled = currentLot != null && currentLot.ID > 0;
             
            }
            catch (Exception e)
            {
                showErrorMsg(e.Message);
            }
            closeWaitForm();
        }
        int selectedInShipId = 0;
        int selectedShipIndex;
        string shipDate;
       
        string selectedShipDriver = "";
          
        
        
       
         
        private void btnDelete_Click(object sender, EventArgs e)
        { 
        }
        protected void query()
        {
            pager1.Bind();
        }
        private void queryGoods()
        {
            showWaitForm();
            try
            {
                query();// loadData();  
            }
            catch (Exception e)
            {
                showErrorMsg(e.Message);
            }
            finally
            {
                // WaitFormService.Close();
                closeWaitForm();
                bbQuery.Enabled = true;
            }
        }
         
        private void bbQuery_ItemClick_1(object sender, ItemClickEventArgs e)
        {
            this.bbQuery.Enabled = false;
            queryGoods();
        }
       
        private void updateObjects(List goods)
        { 
            showWaitForm();
            //WaitFormService.Show(this); 
            try
            {
             //   lgt.update(goods);
                //get updated data 
                query();
            }
            catch (Exception e)
            {
                showErrorMsg(e.Message);
            }
            finally
            {
                // WaitFormService.Close();
                closeWaitForm();
             
            }
             
        }
        string lastSelectedLotId = "";
        private bool getCurrentObject()
        {
            if (selectedRowIndex <0 || selectedRowIndex >= dt.Rows.Count)
            {
                return false;
            }
           
          //  DataRow currentRow = dt.Rows[selectedRowIndex];
            DataRowView dr = (DataRowView)(GetGridViewFilteredAndSortedData(gridView1)[selectedRowIndex]);
            lastSelectedLotId = currentLot == null ? "" : currentLot.lotName;
            currentLot = getWcfObject( new Lot(dr.Row));  
            this.gridControl2.DataSource = null;
            btnAdd.Enabled = true;
    
            return true;
        }
       
        private void btnQuery_Click(object sender, EventArgs e)
        {
            queryGoods();
        }
        private void gridView1_SelectionChanged(object sender, DevExpress.Data.SelectionChangedEventArgs e)
        {
            if (gridView1.FocusedRowHandle <0 || gridView1.FocusedRowHandle == selectedRowIndex)
            {
                return;
            }
            selectedRowIndex = gridView1.FocusedRowHandle;
            // showErrorMsg("selection:"+ selectedRowIndex);
            setCurrentRequestDetail();
        }
        private void initialDataGrid()
        {
            gridView1.OptionsSelection.MultiSelect = true;//按shift / control 多选
            this.gridView1.OptionsBehavior.AutoPopulateColumns = false;
            this.gridView1.FocusRectStyle = DevExpress.XtraGrid.Views.Grid.DrawFocusRectStyle.RowFocus;
            this.gridView1.FocusRectStyle = DevExpress.XtraGrid.Views.Grid.DrawFocusRectStyle.CellFocus;
            this.gridView1.OptionsBehavior.Editable = false;
            //    this.gridView1.OptionsSelection.EnableAppearanceFocusedCell = false;
            this.gridView1.FocusedRowObjectChanged += new DevExpress.XtraGrid.Views.Base.FocusedRowObjectChangedEventHandler(this.gridView1_FocusedRowObjectChanged);
            this.gridView1.DataSourceChanged += new System.EventHandler(this.gridView1_DataSourceChanged);
            //show line number
            this.gridView1.IndicatorWidth = 40;
            this.gridView1.CustomDrawRowIndicator += new DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventHandler(gridView_CustomDrawRowIndicator);
            this.gridView2.IndicatorWidth = 40;
            this.gridView2.CustomDrawRowIndicator += new DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventHandler(gridView_CustomDrawRowIndicator);
          
            gridView2.CustomColumnDisplayText += gridView2_CustomColumnDisplayText;
            gridView2.CustomDrawCell += gridView_CustomDrawCell;
            gridView2.RowCellStyle += gridView_RowCellStyle;
            gridView1.RowCellStyle += gridView_RowCellStyle;
            this.gridView2.FocusedRowObjectChanged += new DevExpress.XtraGrid.Views.Base.FocusedRowObjectChangedEventHandler(this.gridView2_FocusedRowObjectChanged);
            
            gridView1.CustomColumnDisplayText += gridView2_CustomColumnDisplayText;
            gridView1.CustomDrawCell += gridView_CustomDrawCell;
          
        }
   
       private void gridView2_CustomColumnDisplayText(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDisplayTextEventArgs e)
        {
         //   if (sender == gridView2)
            {
                if (e.Column.FieldName == "attType")
                {
                    if (!stockInLocationStatus.ContainsValue(e.DisplayText))
                    {
                        int display = -100;
                        string disTxt = e.DisplayText;
                        try
                        {
                            display = Convert.ToInt16(e.DisplayText);
                            if (sender == gridView2)
                            {
                                e.DisplayText = this.enLotAttType[display];
                            } 
                        }
                        catch
                        {
                            return;
                        }
                    }
                   // e.DisplayText = stockInLocationStatus.ContainsKey(display) ? stockInLocationStatus[display] : display+"";
                }
               
            }
        }
       void gridView_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
       {
           //var currentView = sender as GridView;
           //if (currentView != null && e.RowHandle == currentView.FocusedRowHandle) return;
           Rectangle r = e.Bounds;
           if (e.Column.FieldName == "wms_state" && e.CellValue !=null)
           {
               string a = e.CellValue.ToString();
               string b = e.DisplayText;
               if (b.Equals("待收货"))
               {
                   e.Appearance.ForeColor = Color.Red;
                   e.Appearance.DrawString(e.Cache, e.DisplayText, r);
                   e.Handled = true;
               }
               else if(b.Equals("已收货"))
               {
                   e.Appearance.ForeColor = Color.Gray;
                   e.Appearance.DrawString(e.Cache, e.DisplayText, r);
                   e.Handled = true;
               }
           }
       }
       void gridView_RowCellStyle(object sender,DevExpress.XtraGrid.Views.Grid.RowCellStyleEventArgs e)
       {
            var currentView = sender as GridView;
           if( currentView == null){return;}
           if (!currentView.GetDataRow(e.RowHandle).Table.Columns.Contains("wms_state"))
           {
               return;
           }
           string state = currentView.GetDataRow(e.RowHandle)["wms_state"].ToString().Trim();
           
           if (state == "0")
           {
               return;
           }
           bool isFocused = e.RowHandle == currentView.FocusedRowHandle;
           DevExpress.Utils.AppearanceDefault rowStyle = null;
            DevExpress.Utils.AppearanceDefault appBlueRed = 
               new DevExpress.Utils.AppearanceDefault (Color.White, Color.Red, Color.Empty, Color.Blue, System.Drawing.Drawing2D.LinearGradientMode.Horizontal);
           DevExpress.Utils.AppearanceDefault appYB =
            new DevExpress.Utils.AppearanceDefault(Color.White, Color.Red, Color.Green);
           DevExpress.Utils.AppearanceDefault alertFocus = new DevExpress.Utils.AppearanceDefault(Color.White, Color.Red, Color.Green,  Color.Yellow);
           DevExpress.Utils.AppearanceDefault alert  = new DevExpress.Utils.AppearanceDefault(Color.Red, Color.White );
           DevExpress.Utils.AppearanceDefault passedFocus = new DevExpress.Utils.AppearanceDefault(Color.White, Color.Gray);
           DevExpress.Utils.AppearanceDefault passed = new DevExpress.Utils.AppearanceDefault(Color.Gray, Color.White);
           if (state == "2"  )
           {
               rowStyle = isFocused ? passedFocus : passed;
           }
           else  if (state == "1")
           {
               rowStyle = isFocused ? alertFocus : alert;
           }
           DevExpress.Utils.AppearanceHelper.Apply(e.Appearance, rowStyle);
           /*
           if (sender == this.gridView2)
           {
               if (this.gridView2.GetDataRow(e.RowHandle)["state"].ToString().Trim() == "2")
               {
                   DevExpress.Utils.AppearanceHelper.Apply(e.Appearance, alert);
               }
           }else if(sender == this.gridView1){
                
               if ( state == "2")
               {
                   if (currentView != null && e.RowHandle == currentView.FocusedRowHandle)
                   {
                       DevExpress.Utils.AppearanceHelper.Apply(e.Appearance, alertFocus);
                   }
                   else
                   {
                       DevExpress.Utils.AppearanceHelper.Apply(e.Appearance, alert);
                   }
               }
               else if (state == "1")
               {
                   DevExpress.Utils.AppearanceHelper.Apply(e.Appearance, passed);
               } 
           }
           */
       }
        private void setCurrentRequestDetail()
        {
            btnDel.Enabled = btnUpdate.Enabled = btnAdd.Enabled =false;
            if (!getCurrentObject() || currentLot == null)
            {
                return;
            }
            /// gridView1.FocusedRowHandle = selectedRowIndex;//
            //  gridView1.SelectRow(selectedRowIndex);
            showWaitForm();
            this.txtLotId.Text = currentLot.lotName;
            txtLotDesc.Text = currentLot.description;
          
            try
            {
                isShowingInRequest = true;
                dtAtt = lotClient.queryLotAtts(currentLot.ID);
                closeClient();;
                //selectedInIndex = -1;
             
                this.gridControl2.DataSource = dtAtt;
                initialGridView2Columns(gridView2);
                selectedAttIndex = gridView2.FocusedRowHandle;
                setCurrentInDetail();
                 
              //  this.btnAdd.Enabled = selectedRequest.state != (int)enumInStockOrderStatus.已入库;
                 
             
            }
            catch (Exception e)
            {
                showErrorMsg(e.Message);
            }
            closeWaitForm();
        }
        
        private void btnIn_Click(object sender, EventArgs e)
        {
           
           
        }
        void receiveByItem()
        {
              
        }
 
         
        private void GoodsInForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            //closeClient();;
        }
        protected new void gridview_GotFocus(object sender, EventArgs e)
        {
            if (sender == gridView1)
            {
                //grid4Valid.ForeColor = Color.Blue;
                // gridView4Valid.OptionsSelection.EnableAppearanceHideSelection = true;
                if (!isShowingInRequest)
                {
                    this.setCurrentRequestDetail();
                }
                switchGridViewRowSelection(gridView1, true);
               
            }
           
            else
            {
                switchGridViewRowSelection((GridView)sender, true);
            }
        }
        
        private void txtQuery_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode != Keys.Enter)
            {
                return;
            }
            string barcode = ""; 
            if (string.IsNullOrEmpty(barcode) || barcode.Length<5)
            {
                return;
            }
            DataRow[] drs = this.dt.Select(string.Format("pur_order ='{0}'", barcode)); ;
            if (drs.Length > 0)
            {
                // selectedValidatedItem = dtPickOrdersValidated.Rows.IndexOf(dr0); 
                this.selectedRowIndex = 0;
                foreach (DataRowView drv in GetGridViewFilteredAndSortedData(gridView1))
                {
                    if (drv["orderNo"].ToString().Trim().Equals(barcode))
                    {
                        break;
                    }
                    selectedRowIndex++;
                }
                if (selectedRowIndex >= 0 && dt.Rows.Count > selectedRowIndex)
                {
                    this.gridView1.FocusedRowHandle = selectedRowIndex;
                    setCurrentRequestDetail();
                }
                else
                {
                    showErrorMsg(string.Format("当前列表没定位到单号'{0}'", barcode));
                }
            }
            else
            {
                showErrorMsg(string.Format("当前列表没定位到单号'{0}'",barcode));
            }
                 
           
             }
        private void barBiSyncGoods_ItemClick(object sender, ItemClickEventArgs e)
        {
            initailErpData();
        }
        /// 
        /// 同步erp 信息
        /// 
        private void initailErpData()
        {
            showWaitForm("正在同步商品信息");
            try
            {
                //同步商品信息
                //lWmsGoods lg = new lWmsGoods();
                //lg.getWmsGoods.syncGoods();
                using (ServiceReferenceGoods.GoodsClient lotClient = new ServiceReferenceGoods.GoodsClient())
                {
                    lotClient.syncGoods();
                }
                closeWaitForm();
            }
            catch (Exception e)
            {
                LogHelper.WriteLog(this.GetType(), e);
                // showErrorMsg(e.Message);
                closeWaitForm();
            }
        }
        
        
         
        private void btnQueryShip_Click(object sender, EventArgs e)
        {
 
        }
        void getShipDetails(string shipOrder)
        {
            
        }
        private void btnAddLot_Click(object sender, EventArgs e)
        {
            if (!validLot())
            {
                return;
            }
            WcfLot lot = new WcfLot();
            lot.lotName = txtLotId.Text;
            lot.operater = LoginInfo.UserId;
            lot.description = filtRiskChar(txtLotDesc.Text);
            showWaitForm();
            try
            {
                lotClient.newLot(lot); 
                closeWaitForm();
            }
            catch (Exception er)
            {
             
               showErrorMsg(er.Message);
                closeWaitForm();
            }
            query();
        }
        bool validLot( )
        {
            string lotId = txtLotId.Text;
            lotId = filtRiskChar(lotId);
            if (lotId.Trim().Length < 4)
            {
                showErrorMsg("请输入批次的名称");
                txtLotId.Focus();
                return false;
            }
            string lotdesc = txtLotDesc.Text;
            lotdesc = filtRiskChar(lotdesc);
            if (lotdesc.Trim().Length < 4)
            {
                showErrorMsg("请输入批次的描述");
                txtLotDesc.Focus();
                return false;
            }
            return true;
        }
        private void btnUpdateLot_Click(object sender, EventArgs e)
        {
            if (!validLot())
            {
                return;
            }
            currentLot.lotName = filtRiskChar(txtLotId.Text);
            currentLot.description = filtRiskChar(txtLotDesc.Text);
            currentLot.operater = LoginInfo.UserId;
            showWaitForm();
            try
            {
              
                lotClient.updateLot(currentLot);
                 
            }
            catch (Exception er)
            {
                
                showErrorMsg(er, "出错了");
              
                 
            }
            closeClient();;
            closeWaitForm();
            query();
        }
          WcfLot getWcfObject(Lot dbObj)
        {
            WcfLot wcfObj = new WcfLot();
            wcfObj.ID = dbObj.ID;
            wcfObj.lotName = dbObj.lotName;
            wcfObj.description = dbObj.description;
            wcfObj.operater = dbObj.operater;
            return wcfObj;
        }
          WcfLotAtt getWcfObject(LotAtt dbObj)
        {
            WcfLotAtt wcfObj = new WcfLotAtt();
            wcfObj.ID = dbObj.ID;
            wcfObj.lotId = dbObj.lotId;
            wcfObj.attName = dbObj.attName;
            wcfObj.attType = dbObj.attType;
            wcfObj.isList = dbObj.isList;
            wcfObj.listId = dbObj.listId;
            wcfObj.isOptional = dbObj.isOptional;
            wcfObj.operater = dbObj.operater;
            return wcfObj;
        }
          bool lotAttValid(WcfLotAtt lotAtt)
          {
              lotAtt.attName = filtRiskChar(this.txtAttributeName.Text);
              lotAtt.attType = ((Colitem)this.comAttType.SelectedItem).key;
              lotAtt.lotId = currentLot.ID;
              lotAtt.operater = LoginInfo.UserId;
              lotAtt.isOptional = chkStock.Checked;
              try
              {
                  string listid = filtRiskChar(txtAttListId.Text);
                  if (!string.IsNullOrEmpty(listid))
                  {
                      int id = Convert.ToInt16(filtRiskChar(txtAttListId.Text));
                      lotAtt.listId = id;
                      lotAtt.isList = true;
                  }
              }
              catch (Exception er)
              {
                  showErrorMsg(er, "请输入正确的ID");
                  txtAttListId.Focus();
                  return false;
              }
              return true;
          }
          private void btnAdd_Click(object sender, EventArgs e)
          {
              if (currentLot ==null || currentLot.ID == 0)
              {
                  return;
              }
              WcfLotAtt lotAtt = new WcfLotAtt();
              if (!lotAttValid(lotAtt))
              {
                  return;
              }
              try
              {
                  showWaitForm();
                  lotClient.newLotAtt(lotAtt);
                  closeClient();;
              }
              catch (Exception er)
              {
                  closeWaitForm();
                  showErrorMsg(er, "出错了");
                  closeClient();;
                  return;
              }
              closeWaitForm();
              setCurrentRequestDetail();
          }
          private void btnUpdate_Click(object sender, EventArgs e)
          {
              if (currentDetail == null || currentDetail.ID == 0)
              {
                  return;
              }
              if (!lotAttValid(currentDetail))
              {
                  return;
              }
              try
              {
                  showWaitForm();
                  lotClient.updateLotAtt(currentDetail);
                  closeClient();;
              }
              catch (Exception er)
              {
                  closeWaitForm();
                  showErrorMsg(er, "出错了");
                  closeClient();;
                  return;
              }
              closeWaitForm();
              setCurrentRequestDetail();
          }
          private void btnDel_Click(object sender, EventArgs e)
          {
              if (currentDetail == null || currentDetail.ID == 0)
              {
                  return;
              }
              if (!lotAttValid(currentDetail))
              {
                  return;
              }
              try
              {
                   DialogResult r = MessageBox.Show(string.Format("确定要删除批次属性吗?",currentDetail.attName),
                                                   
                                                 "确认删除", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                   if (r == DialogResult.Yes)
                   {
                       showWaitForm();
                       lotClient.deleteLotAtt(currentDetail);
                       closeClient();;
                   }
              }
              catch (Exception er)
              {
                  closeWaitForm();
                  showErrorMsg(er, "出错了");
                  closeClient();;
                  return;
              }
              closeWaitForm();
              setCurrentRequestDetail();
          }
          private void btnDelLot_Click(object sender, EventArgs e)
          {
          }
          private void btnInitialSkus_Click(object sender, EventArgs e)
          {
            //  stkLocClient.formatLocName();
            //   stkLocClient.Close();
           // stkLocClient.initalSkus(true, 11);
          //  stkLocClient.initalSkus(true, 13);
          //  stkLocClient.initalSkus(true, 15);
            stkLocClient.initalSkus(true, 0);
            closeClient();
           // stkLocClient.initalSkus(true, 3); 
          //  closeClient();
            /*
            */
        }
          private void btnSku_Click(object sender, EventArgs e)
          {
/*
            string date = "20240801";
            string prddate =Util.getShortDateString(date);
            DateTime validdate = Util.pareseDateString(prddate).AddDays(360);
            string svd = validdate.ToShortDateString();
            svd = Util.getShortDateString(svd);
            
             *   initial sku values 
             *   truncate table t_sku;
                 truncate table t_skuvalue;
                 update [t_wmsStock] set skuid =0 ;
             */
            DialogResult dr = MessageBox.Show("警告! 将初始化库存SKU信息,继续吗?", "警告", MessageBoxButtons.YesNo);
              if (dr == System.Windows.Forms.DialogResult.No)
              {
                  return;
              }
              try
              {
                  stkLocClient.initalSkus(false,0);
              //  stkLocClient.initalSkus(false,13);
              //  stkLocClient.initalSkus(false, 15);
                 stkLocClient.Close();
              }
              catch (Exception er)
              {
                  showErrorMsg(er);
              }
            showInfoMsg("初始化完毕");
          }
        private void gridControl2_Click(object sender, EventArgs e)
        {
        }
    }
}