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.OrderService;
using DeiNiu.wms.win.utils;
namespace DeiNiu.wms.win
{
    public partial class StockOrders : BasicRibbonForm, IPicker
    {
      
        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 DtGv;
      //  DataTable dtIndetail;
        private int selectedRowIndex = -1;
        //to show in detail
        int selectedAttIndex = -1;
        string detailGoodsName;
        decimal avCount = 0;
        int selectedAttId;
        int selectedAttDetailId = -1;
        WcfWmsOrderRequest wcfRequest;
        WcfWmsOrderDetail currentDetail;
        private bool isShowingInRequest = true;
        public StockOrders()
        {
         
            InitializeComponent();
            try
            {
                initialControls();
            }
            catch (Exception er)
            {
                showErrorMsg(er);
            }
            //    loadData();
        }
        #region initialControls
        private void initialControls()
        { 
            setDatePiker(dateEditFrom, dateEditTo);
            initialComboBoxes();
            initialPagerControls();
            initialDataGrid();
            initialQueryInput(); 
            setValidationRule();
           
        }
        private void initialComboBoxes()
        {
            orderType.Remove((int)enumOrderType.销售出库);
            orderType.Remove((int)enumOrderType.补货出库);
            orderType.Remove((int)enumOrderType.退供应商);
            orderType.Remove((int)enumOrderType.盘点通知);
            orderType.Remove((int)enumOrderType.仓间调拨);
            orderType.Remove((int)enumOrderType.库区转移);
            initialComboBoxs(comTypeQ, orderType,true);
            initialComboBoxs(comType, orderType, false);
            initialComboBoxs(comStatusQ, orderStatus, true);
            initialComboBoxs(comWhtypeFrom, whType,false);
            initialComboBoxs(comToWh, whType,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)
        {
            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);
            setupGridView(gridView, false);
            
            GridColumn myCol1 = new GridColumn() { Caption = "单号", Visible = true, FieldName = "orderNo" };
            GridColumn myCol2 = new GridColumn() { Caption = "商品ID", Visible = true, FieldName = "goodsId" };
            GridColumn myCol3 = new GridColumn() { Caption = "商品名称", Visible = true, FieldName = "goodsName" };
            GridColumn myCol4 = new GridColumn() { Caption = "生产日期", Visible = true, FieldName = "productDate" };
            GridColumn myCol5 = new GridColumn() { Caption = "失效日期", Visible = true, FieldName = "validDate" };
            GridColumn myCol6 = new GridColumn() { Caption = "申请数量", Visible = true, FieldName = "count" };
            GridColumn myCol61 = new GridColumn() { Caption = "库存数量", Visible = true, FieldName = "avCount" };
            GridColumn myCol7 = new GridColumn() { Caption = "价格", Visible = true, FieldName = "price" };
            GridColumn myCol8 = new GridColumn() { Caption = "出库房", Visible = true, FieldName = "whtype" };
            GridColumn myCol9 = new GridColumn() { Caption = "入库房", Visible = true, FieldName = "toWhType" };
            GridColumn myCol10 = new GridColumn() { Caption = "货位", Visible = true, FieldName = "locationId" };
            GridColumn myCol101 = new GridColumn() { Caption = "货位状态", Visible = true, FieldName = "locState" };
            GridColumn myCol102 = new GridColumn() { Caption = "库存状态", Visible = true, FieldName = "storeState" };
            GridColumn myCol11 = new GridColumn() { Caption = "客户", Visible = true, FieldName = "custName" };
            GridColumn myCol111 = new GridColumn() { Caption = "区域", Visible = true, FieldName = "partion" };
            GridColumn myCol1111 = new GridColumn() { Caption = "区域", Visible = true, FieldName = "partionName" };
            if (gridView == gridView1)
            {
                GridColumn myCol21 = new GridColumn() { Caption = "类型", Visible = true, FieldName = "orderType", MinWidth = 80 };
                GridColumn myCol31 = new GridColumn() { Caption = "状态", Visible = true, FieldName = "state" ,MinWidth=120};
                GridColumn myCol41 = new GridColumn() { Caption = "创建人", Visible = true, FieldName = "requestByName" };
                    
                gridView.Columns.Add(myCol1);
                gridView.Columns.Add(myCol21);
                gridView.Columns.Add(myCol31);
                gridView1.Columns.Add(myCol41);
            
            }else
            if (gridView == gridView2)
            {
                // GridColumn colChk = new GridColumn() { Caption = CheckBoxField, Visible = true, FieldName = CheckBoxField };
                //  gridView.Columns.Add(colChk);
                // GridCheckEdit(gridView, CheckBoxField, 50);
                GridColumn myCol41 = new GridColumn() { Caption = "规格", Visible = true, FieldName = WmsGoods.exfields.spec.ToString(), Width = 100 };
                GridColumn myCol51 = new GridColumn() { Caption = "单位", Visible = true, FieldName = WmsGoods.exfields.unit.ToString() };
                gridView.Columns.Add(myCol3);
              // gridView.Columns.Add(myCol2);
                
                gridView.Columns.Add(myCol4);
                gridView.Columns.Add(myCol5);
                gridView.Columns.Add(myCol6);
                gridView.Columns.Add(myCol61);
                gridView.Columns.Add(myCol51);
                gridView.Columns.Add(myCol41);
        
                gridView.Columns.Add(myCol7);
                gridView.Columns.Add(myCol8);
                gridView.Columns.Add(myCol9);
                gridView.Columns.Add(myCol10); 
                gridView.Columns.Add(myCol101); 
                gridView.Columns.Add(myCol102);
                gridView.Columns.Add(myCol11);
                gridView.Columns.Add(myCol1111);
               // gridView.Columns.Add(myCol111);
               
            }
            //to show bottom scroll bar
            gridView.OptionsView.ColumnAutoWidth = false;
            gridView.BestFitColumns();
        }
        
        
        #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();
            clearData();
            try
            {
                string orderNo = this.txtOrderNo.Text.Trim();
                string query = (string.IsNullOrEmpty(orderNo) ? ""
                    : string.Format("{0} =#'{1}';", WmsOrderRequest.fields.orderNo, filtRiskChar(txtOrderNo.Text.Trim())));
                   
                query+=  string.Format("{0} =#'{1}';", WmsOrderRequest.fields.requestBy,  LoginInfo.UserId);
                // this.splashScreenManager1.ShowWaitForm();
                if (string.IsNullOrEmpty(orderNo))
                {
                    query += (this.dateEditFrom.Text.Trim().Length == 0 ? "" : string.Format("{0} >= # '{1}';", WmsOrderRequest.fields.orderDate.ToString(), dateEditFrom.DateTime))
                          + (this.dateEditTo.Text.Trim().Length == 0 ? "" : string.Format("{0} <= # '{1}';", WmsOrderRequest.fields.orderDate.ToString(), dateEditTo.DateTime));
                    query += (this.comStatusQ.SelectedIndex <= 0 ? "" : string.Format("{0} = #{1};", WmsOrderRequest.fields.state.ToString(), ((Colitem)this.comStatusQ.SelectedItem).key))
                            + (this.comTypeQ.SelectedIndex <= 0 ? "" : string.Format("{0} = #{1};", WmsOrderRequest.fields.orderType.ToString(), ((Colitem)this.comTypeQ.SelectedItem).key))
;
                }
                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 = orderClient.query(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 (wcfRequest !=null)
                {
                    selectedRowIndex = -1;
                    DataRow dr = dt.Rows.Find(wcfRequest.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 clearData()
        {
            txtDetailDesc.Text = txtCount.Text = txtOrderDesc.Text = txtOrderNo.Text = lbDetailName.Text = lbOrderNo.Text = "";
        }
         
        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);
            }
        }
       
        
        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]);
            detailGoodsName = dr["goodsName"].ToString();
            selectedAttId = Convert.ToInt32(dr["id"].ToString());
            avCount = Convert.ToDecimal( dr["avCount"].ToString());
            currentDetail = getWcfObject( new WmsOrderDetail(dr.Row));
            return true;
        }
        private void setCurrentInDetail()
        {
           
            if (!getCurrentAttObject() || string.IsNullOrEmpty( detailGoodsName))
            {
                return;
            }
            /// gridView1.FocusedRowHandle = selectedRowIndex;//
            //  gridView1.SelectRow(selectedRowIndex);
            showWaitForm();
            try
            {
               
                txtDetailDesc.Text = currentDetail.description;
                txtCount.Text = currentDetail.count+"";
                lbDetailName.Text = detailGoodsName;
                setButton();
             
            }
            catch (Exception e)
            {
                showErrorMsg(e.Message);
            }
            closeWaitForm();
        }
         
         
        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 lastSelectedOrderNo = "";
        private bool getCurrentObject()
        {
            if (selectedRowIndex <0 || selectedRowIndex >= dt.Rows.Count)
            {
                return false;
            }
           
          //  DataRow currentRow = dt.Rows[selectedRowIndex];
            DataRowView dr = (DataRowView)(GetGridViewFilteredAndSortedData(gridView1)[selectedRowIndex]);
            lastSelectedOrderNo = wcfRequest == null ? "" : wcfRequest.orderNo;
            wcfRequest = getWcfObject( new WmsOrderRequest(dr.Row));  
            this.gridControl2.DataSource = null;
            setButton();
           
    
            return true;
        }
  
    	public  WcfWmsOrderRequest getWcfObject( WmsOrderRequest dbObj){   
    
          WcfWmsOrderRequest wcfObj = new  WcfWmsOrderRequest();     
          wcfObj.id = dbObj.ID;  
          wcfObj.orderNo = dbObj.orderNo;  
          wcfObj.orderType = dbObj.orderType;  
          wcfObj.orderTypeName = dbObj.orderTypeName;  
          wcfObj.ownerCode = dbObj.ownerCode;  
          wcfObj.owner = dbObj.owner;  
          wcfObj.state = dbObj.state;  
          wcfObj.orderDate = dbObj.orderDate;  
          wcfObj.description = dbObj.description;  
          wcfObj.operater = dbObj.operater;  
          wcfObj.requestBy = dbObj.requestBy;  
          wcfObj.requestDate = dbObj.requestDate;  
          wcfObj.approvedBy = dbObj.approvedBy;  
          wcfObj.approveDate = dbObj.approveDate;  
          wcfObj.toWareHouse = dbObj.toWareHouse;  
          wcfObj.WhType = dbObj.WhType;  
          wcfObj.toWhType = dbObj.toWhType;  
          wcfObj.venderNo = dbObj.venderNo;  
          wcfObj.customerId = dbObj.customerId;  
          wcfObj.referOrderNo = dbObj.referOrderNo;  
          
           return wcfObj;
    
         
        }
        private void setButton()
        {
            bool enable = wcfRequest != null && (wcfRequest.state == (int)enumOrderStatus.创建);
                  //|| wcfRequest.state == (int)enumOrderStatus.已驳回);
           
            btnOrderUpdate.Enabled = btnDelOrder.Enabled = btnSubmit.Enabled=
              btnPickItems.Enabled = btnDetailDel.Enabled =btnUpdateDetail.Enabled = enable;
             
        }
       
        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 == gridView1)
            {
                if (e.Column.FieldName == "state")
                {
                    if (!orderStatus.ContainsValue(e.DisplayText))
                    {
                        int display = -100;
                        string disTxt = e.DisplayText;
                        try
                        {
                            display = Convert.ToInt32(e.DisplayText);
                            
                             
                                e.DisplayText = this.orderStatus[display];
                              
                        }
                        catch
                        {
                            return;
                        }
                    }
                } else if (e.Column.FieldName == "orderType")
                {
                    if (!orderType.ContainsValue(e.DisplayText))
                    {
                        int display = -100;
                        string disTxt = e.DisplayText;
                        try
                        {
                            display = Convert.ToInt32(e.DisplayText);
                          
                            {
                                e.DisplayText = this.orderType[display];
                            }
                        }
                        catch
                        {
                            return;
                        }
                    }
                }
            }
           else if (sender == gridView2)
            {
                if (e.Column.FieldName == "whtype" || e.Column.FieldName == "toWhType")
                {
                    if (!whType.ContainsValue(e.DisplayText))
                    {
                        int display = -100;
                        string disTxt = e.DisplayText;
                        try
                        {
                            display = Convert.ToInt32(e.DisplayText);
                            {
                                e.DisplayText = this.whType[display];
                            }
                        }
                        catch
                        {
                            return;
                        }
                    }
                }  
                else if (e.Column.FieldName == "locState" || e.Column.FieldName == "storeState")
                {
                    if (!this. stockState.ContainsValue(e.DisplayText))
                    {
                        int display = -100;
                        string disTxt = e.DisplayText;
                        try
                        {
                            display = Convert.ToInt32(e.DisplayText);
                            {
                                e.DisplayText = this.stockState[display];
                            }
                        }
                        catch
                        {
                            return;
                        }
                    }
                }
               
            }
        }
       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 == "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()
        {
            btnDetailDel.Enabled = btnOrderUpdate.Enabled = btnPickItems.Enabled =false;
            if (!getCurrentObject() || wcfRequest == null)
            {
                return;
            }
            /// gridView1.FocusedRowHandle = selectedRowIndex;//
            //  gridView1.SelectRow(selectedRowIndex);
            showWaitForm();
            comType.SelectedIndex = wcfRequest.orderType-6; 
            lbOrderNo.Text = wcfRequest.orderNo;
            txtOrderDesc.Text = wcfRequest.description;
            comToWh.SelectedIndex = wcfRequest.toWhType;
            comWhtypeFrom.SelectedIndex = wcfRequest.WhType;
            txtVender.Text = wcfRequest.venderNo;
            try
            {
                isShowingInRequest = true;
                DtGv = orderClient.getDetail(wcfRequest.orderNo);
                addCheckField(DtGv);//add checkbox
                closeClient();;
                //selectedInIndex = -1;
             
                this.gridControl2.DataSource = DtGv;
                initialDataGridColumns(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 btnQueryShip_Click(object sender, EventArgs e)
        {
 
        }
        void getShipDetails(string shipOrder)
        {
            
        }
        private void btnAddLot_Click(object sender, EventArgs e)
        {
            if (!validOrder())
            {
                return;
            }
 
            showWaitForm();
            try
            {
                
                closeWaitForm();
            }
            catch (Exception er)
            {
             
               showErrorMsg(er.Message);
                closeWaitForm();
            }
            query();
        }
        bool validOrder( )
        { 
            wcfRequest.orderType = ((Colitem)comType.SelectedItem).key;
            wcfRequest.requestBy = LoginInfo.UserId;
            wcfRequest.requestByName = LoginInfo.Account;
            wcfRequest.description = txtOrderDesc.Text; 
            wcfRequest.WhType = comWhtypeFrom.SelectedIndex;
            wcfRequest.toWhType = comToWh.SelectedIndex;
            wcfRequest.venderNo = txtVender.Text;
          //  wcfRequest.venderName 
            enumOrderType type =(enumOrderType) wcfRequest.orderType;
            if (type == enumOrderType.退供应商)
            {
                if (String.IsNullOrEmpty(wcfRequest.venderNo))
                {
                    showErrorMsg("请输入供应商代码");
                    return false;
                }
            }
            return true;
        }
        private void btnUpdateLot_Click(object sender, EventArgs e)
        {
          
        }
 
        
        
        
          private void btnUpdate_Click(object sender, EventArgs e)
          {
              if (!validOrder())
              {
                  return;
              } 
              wcfRequest.description = filtRiskChar(txtOrderDesc.Text);
            
              showWaitForm();
              try
              {
                  orderClient.update(wcfRequest);
              }
              catch (Exception er)
              {
                  showErrorMsg(er, "出错了");
              }
              closeClient(); ;
              closeWaitForm();
              query();
          }
           
           
          public void setPickedData(DataTable dt)
          {
              if (String.IsNullOrEmpty(wcfRequest.orderNo))
              {
                  showErrorMsg("请先创建单据");
                  return;
              }
              WcfWmsOrderDetail od;
              List ods = new List();
              foreach (DataRow dr in dt.Rows)
              {
                  od = getWcfObject(new WmsOrderDetail(dr));
                  od.orderNo = wcfRequest.orderNo;
                if (dt.Columns.Contains("avCount"))
                {
                    od.count = Convert.ToDecimal(dr["avCount"].ToString());
                }
                 // od.description = txtDetailDesc.Text.Trim();
                  od.whtype = wcfRequest.WhType;
                  od.toWhType = wcfRequest.toWhType;
                  ods.Add(od);
              }
              orderClient.addDetail(wcfRequest.orderType, ods.ToArray());
             
              loadData(); 
              closeClient();
          }
          WcfWmsOrderDetail getWcfObject(WmsOrderDetail dbObj)
          {
              WcfWmsOrderDetail wcfObj = new WcfWmsOrderDetail();
              wcfObj.id = dbObj.ID;
              wcfObj.orderNo = dbObj.orderNo;
              wcfObj.skuId = dbObj.skuId;
              wcfObj.skuCode = dbObj.skuCode;
              wcfObj.goodsId = dbObj.goodsId;
              wcfObj.batch = dbObj.batch;
              wcfObj.productDate = dbObj.productDate;
              wcfObj.validDate = dbObj.validDate;
              wcfObj.count = dbObj.count;
              wcfObj.price = dbObj.price;
              wcfObj.state = dbObj.state;
              wcfObj.whtype = dbObj.whtype;
              wcfObj.toWhType = dbObj.toWhType;
              wcfObj.locationId = dbObj.locationId;
              wcfObj.description = dbObj.description;
              wcfObj.operater = dbObj.operater;
            wcfObj.unit = dbObj.unit;
            wcfObj.goodsName = dbObj.goodsName;
            wcfObj.price = dbObj.price;
            wcfObj.partion = dbObj.partion;
         
              return wcfObj;
          }
          private void btnCreate_Click(object sender, EventArgs e)
          {
              wcfRequest = new WcfWmsOrderRequest();
              validOrder();
             // wcfRequest.toWareHouse=comw
              lbOrderNo.Text = wcfRequest.orderNo = orderClient.add(wcfRequest); 
              btnPickItems.Enabled = !String.IsNullOrEmpty(wcfRequest.orderNo);
              query();
          }
          private void btnPickItems_Click(object sender, EventArgs e)
          {
              if (wcfRequest.state == (int)enumOrderStatus.创建)
                 // || wcfRequest.state == (int)enumOrderStatus.已驳回)
              {
                  StockPicker sp = new StockPicker();
                  sp.pickOwner = this;
                  sp.setWhType(wcfRequest.WhType);
                  sp.ShowDialog();
              }
             
          }
         
          private void btnUpdateDetail_Click(object sender, EventArgs e)
          {
              if (currentDetail == null || currentDetail.id == 0)
              {
                  return;
              }
              try
              {
                  currentDetail.count = Convert.ToDecimal(txtCount.Text.Trim());
                  
                  if (avCount < currentDetail.count && currentDetail.skuId>0)
                  {
                     
                      showErrorMsg("输入正确的数量");
                      txtCount.Focus();
                      return;
                  }
                  currentDetail.description = txtDetailDesc.Text;
              }
              catch (Exception er)
              {
                  showErrorMsg("输入正确的数量");
                  txtCount.Focus();
                  return;
              } 
              orderClient.updateDetail(currentDetail);
              closeClient();
              setCurrentRequestDetail();// setCurrentInDetail();
          }
          private void btnSubmit_Click(object sender, EventArgs e)
          {
              wcfRequest.state =(int) enumOrderStatus.待核准;
              orderClient.update(wcfRequest);
              int rt = orderClient.update(wcfRequest);  
              if (rt > 0)
              {
                  showInfoMsg("提交成功");
              }
              query();
              closeClient();
          }
          private void btnDelOrder_Click(object sender, EventArgs e)
          {
              
              if (wcfRequest == null || wcfRequest.id == 0)
              {
                  return;
              }
             
              try
              {
                  DialogResult r = MessageBox.Show(string.Format("确定要删除 {0} 吗?", wcfRequest.orderNo),
                                                "确认删除", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                  if (r == DialogResult.Yes)
                  {
                      showWaitForm();
                      int rt = orderClient.delete(wcfRequest); closeClient(); ;
                      if (rt > 0)
                      {
                          showInfoMsg("删除成功");
                      }
                  }
                  else
                  {
                      return;
                  }
              }
              catch (Exception er)
              {
                  closeWaitForm();
                  showErrorMsg(er, "出错了");
                  closeClient(); ;
                  return;
              }
              closeWaitForm();
              query();
          }
          
          private void btnDetailDel_Click(object sender, EventArgs e)
          {
              if (currentDetail == null || currentDetail.id == 0)
              {
                  return;
              }
              // if (!lotAttValid(currentDetail))
              {
                  //      return;
              }
              try
              {
                  DialogResult r = MessageBox.Show(string.Format("确定要删除 {0} 吗?", detailGoodsName),
                                                "确认删除", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                  if (r == DialogResult.Yes)
                  {
                      showWaitForm();
                         orderClient.deleteDetail(currentDetail);
                         closeClient();;
                  }
              }
              catch (Exception er)
              {
                  closeWaitForm();
                  showErrorMsg(er, "出错了");
                  closeClient(); ;
                  return;
              }
              closeWaitForm();
              setCurrentRequestDetail();
          }
        private void simpleButton1_Click(object sender, EventArgs e)
        {
          DataTable dt=  orderClient.getDetail("OBS23082300002");
        }
    }
}