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.ServiceReferenceGoods;
using DeiNiu.wms.win.utils.print;
namespace DeiNiu.wms.win
{
    public partial class StockPandianNewForm : BasicRibbonForm
    {
        //  lWmsGoods lgt = new lWmsGoods();
        private string fieldName = WmsLocation.fields.locationId.ToString();
        private string fieldGoodType = WmsLocation.fields.whGoodsType.ToString();
        private string lastQuery = "";
        private DataTable dtPandian;
        string queryStr = "";
        private DataTable dtDetail;
        private int selectedRowIndex = -1;
        private string currentOrderNo;
        private WmsStockPandian currentPandian;
        public StockPandianNewForm()
        {
            InitializeComponent();
            try
            {
                initialControls();
            }
            catch (Exception er)
            {
                showErrorMsg(er);
            }
            //    loadData();
        }
        #region initialControls
        private void initialControls()
        {
            btnDetail.Enabled = btnDel.Enabled = btnStart.Enabled = btnPrint.Enabled = false;
            setDatePiker(dateEditFrom, dateEditTo);
            initialComboBoxes();
            initialPagerControls();
            initialDataGrid();
            initialQueryInput();
            setValidationRule();
            // setDatePiker(txtStartQ,txtDateEndQ);
        }
        private void initialComboBoxes()
        {
            //initialComboBoxe(comboType, this.stkdiff);
            this.comboState.Properties.TextEditStyle = TextEditStyles.DisableTextEditor;
            combNotice.Properties.TextEditStyle = TextEditStyles.DisableTextEditor;
            combNoticeQ.Properties.TextEditStyle = TextEditStyles.DisableTextEditor;
            comboStatusQ.Properties.TextEditStyle = TextEditStyles.DisableTextEditor;
            combNotice.SelectedIndex = 0;
            combNoticeQ.SelectedIndex = 0;
            initialComboBoxs(comboStatusQ, enmPandianStatus, true);
            initialComboBoxs(comboState, this.stockState, false);
            Node[] nds = { };
            DataRow[] drs = Park.getDictionary(true).Select("flag >0");
            foreach (DataRow dr in drs)
            {
                int flag = Convert.ToInt32(dr["flag"].ToString());
                int parentId = Convert.ToInt32(dr["id"].ToString());
                DataRow[] drss = Park.getDictionary(false).Select("parentId =" + parentId);
                switch (flag)
                {
                    case 1001:
                        initialComboBoxs(this.comboBoGoodsType, drss); //商品类型
                        break;
                    case 2005:
                        initialComboBoxs(this.comboBoPart, drss);//分区
                        break;
                }
            }
            initialComboBoxs(this.comboStkType, whType, false);
            initialComboBoxs(this.comTypeQ, enumPandianType);
            initialComboBoxs(this.comPType, enumPandianType, false);
            comPType.SelectedIndex = enumPandianType.Count - 1;
        }
        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, true);
            //   gridviewGoodsType.PopulateColumns();
            gridview.Columns.Clear();
            // gridviewGoodsType.Columns.Remove(gridviewGoodsType.Columns["DealerPrice"]); 
            GridColumn myCol0 = new GridColumn() { Caption = "ID", Visible = true, FieldName = "id" };
            myCol0.Visible = false;
            GridColumn myCol1 = new GridColumn() { Caption = "盘点单号", Visible = true, FieldName = WmsStockPandian.fields.orderNo.ToString() };
            GridColumn myCol2 = new GridColumn() { Caption = "状态", Visible = true, FieldName = WmsStockPandian.fields.status.ToString() };
            GridColumn myCol3 = new GridColumn() { Caption = "开始时间", Visible = true, FieldName = WmsStockPandian.fields.startTime.ToString() };
            GridColumn myCol4 = new GridColumn() { Caption = "结束时间", Visible = true, FieldName = WmsStockPandian.fields.endTime.ToString() };
            GridColumn myCol5 = new GridColumn() { Caption = "创建人", Visible = true, FieldName = "em_name" };
            GridColumn myCol6 = new GridColumn() { Caption = "盘点类型", Visible = true, FieldName = WmsStockPandian.fields.type.ToString() };
            GridColumn myCol7 = new GridColumn() { Caption = "创建时间", Visible = true, FieldName = "createtime" };
            GridColumn myCol8 = new GridColumn() { Caption = "通知ERP", Visible = true, FieldName = WmsStockPandian.fields.noticeErp.ToString() };
            gridview.Columns.Add(myCol1);
            gridview.Columns.Add(myCol6);
            gridview.Columns.Add(myCol2);
            gridview.Columns.Add(myCol3);
            gridview.Columns.Add(myCol4);
            gridview.Columns.Add(myCol5);
            gridview.Columns.Add(myCol8);
            gridview.Columns.Add(myCol7);
            //to show bottom scroll bar
            gridview.OptionsView.ColumnAutoWidth = false;
            gridview.BestFitColumns();
            // gridview.Focus();
        }
        #endregion
        ///   
        /// loading data
        ///   
        private int loadData()
        {
            //this.gridviewGoodsType.DataSource = lgt.GetAllActiveData().Tables[0].DefaultView;
            gridControl1.DataSource = null;
            showWaitForm();
            try
            {
                // this.splashScreenManager1.ShowWaitForm(); 
                //   isWhLocationQuery =(comboBoWarehouse.SelectedIndex > 0 || txtLocation.Text.Trim().Length > 0);
                queryStr = string.IsNullOrEmpty(filtRiskChar(txtorderQ.Text.Trim())) ? "" :
                          string.Format("{0} = #{1};", WmsStockPandian.fields.orderNo.ToString(), filtRiskChar(txtorderQ.Text.Trim()));
                queryStr += (this.comTypeQ.SelectedIndex <= 0 ? "" : string.Format("{0} = #{1};", WmsStockPandian.fields.type.ToString(), ((Colitem)this.comTypeQ.SelectedItem).key))
                      + (this.combNoticeQ.SelectedIndex <= 0 ? "" : string.Format("{0} = #{1};", WmsStockPandian.fields.noticeErp.ToString(), this.combNoticeQ.SelectedIndex == 1 ? 0 : 1))
                              + (this.comboStatusQ.SelectedIndex <= 0 ? "" : string.Format("{0} = #{1};", WmsStockPandian.fields.status.ToString(), ((Colitem)this.comboStatusQ.SelectedItem).key)) 
                             + (this.dateEditFrom.Text.Trim().Length == 0 ? "" : string.Format("{0} >= # '{1}';","createtime", dateEditFrom.DateTime))
                             + (this.dateEditTo.Text.Trim().Length == 0 ? "" : string.Format("{0} <= # '{1}';", "createtime", dateEditTo.DateTime));
                            ;
                this.pager1.PageCurrent = lastQuery.Equals(queryStr) ? this.pager1.PageCurrent : 1; //根据查询条件的变化给pager赋值
                int start = (pager1.PageSize * (pager1.PageCurrent - 1) + 1);
                int end = (pager1.PageSize * pager1.PageCurrent);
                lastQuery = queryStr;
                DataSet ds = stkLocClient.queryPandianOrders(queryStr, start, end);
                closeClient();
                dtPandian = 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;
                //    dtSum.PrimaryKey = new DataColumn[] { dtSum.Columns["goodsId"], dtSum.Columns["batch"] };
                this.gridControl1.DataSource = dtPandian.DefaultView;
                //  gridView1.OptionsView.ColumnAutoWidth = true;
                initialDataGridColumns(this.gridView1);
                //update selected row index to the last updated one.
                if (!string.IsNullOrEmpty(currentOrderNo))
                {
                    DataRow[] drs = dtPandian.Select(string.Format("orderNo='{0}'", currentOrderNo));
                    DataRow dr = null;
                    if (drs.Length > 0)
                    {
                        dr = drs[0];
                    }
                    if (dr != null)
                    {
                        selectedRowIndex = dtPandian.Rows.IndexOf(dr);
                        if (selectedRowIndex > 0 && dtPandian.Rows.Count > selectedRowIndex)
                        {
                            // gridView1.SelectRow(selectedRowIndex);
                            gridView1.FocusedRowHandle = selectedRowIndex;
                            //  gridView1.MakeRowVisible(selectedRowIndex);
                        }
                    }
                    else
                    {
                        gridView1.FocusedRowHandle = 0;
                        gridView1.SelectRow(0);
                    }
                    //gridView1.FocusedRowHandle = selectedRowIndex;
                }
                else
                {
                    gridView1.FocusedRowHandle = 0;
                    gridView1.SelectRow(0);
                }
                if (dtPandian.Rows.Count > 0 && selectedRowIndex == -1)
                {
                    selectedRowIndex = 0;
                }
                setCurrentRequestDetail();
                closeWaitForm();
                return cnt;// lgt.getRowCount(query);
                // return lgt.GetGoodType.QueryCount(); 
            }
            catch (Exception er)
            {
                showErrorMsg(er, er.Message);
            }
            return 0;
        }
        ///   
        /// 分页控件产生的事件  
        ///   
        private int pager_EventPaging(DeiNiu.Controls.pager.EventPagingArg e)
        {
            //  selectedRowIndex = 0; //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
        }
        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.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(gridView1_CustomDrawRowIndicator);
            gridView1.CustomColumnDisplayText += gridView1_CustomColumnDisplayText;
        }
        //显示行的序号    
        private void gridView1_CustomDrawRowIndicator(object sender, RowIndicatorCustomDrawEventArgs e)
        {
            if (e.Info.IsRowIndicator && e.RowHandle >= 0)
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }
        protected void query()
        {
            pager1.Bind();
        }
        private void queryGoods()
        {
            showWaitForm();
            try
            {
                query();// loadData();  
            }
            catch (Exception e)
            {
                showErrorMsg(e, 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(wgoods);
                //get updated data 
                query();
            }
            catch (Exception e)
            {
                showErrorMsg(e, e.Message);
            }
            finally
            {
                // WaitFormService.Close();
                closeWaitForm();
            }
        }
        private void txtpinyin_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                loadData();
            }
        }
        private void btnQuery_Click_1(object sender, EventArgs e)
        {
            query();
        }
        private void gridView1_CustomColumnDisplayText(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDisplayTextEventArgs e)
        {
            if (e.Column.FieldName == "status")
            {
                if (!stockState.ContainsValue(e.DisplayText))
                {
                    int display = -100;
                    string disTxt = e.DisplayText;
                    try
                    {
                        display = Convert.ToInt32(e.DisplayText);
                        e.DisplayText = enmPandianStatus[display];
                    }
                    catch
                    {
                        return;
                    }
                }
            }
            else if (e.Column.FieldName == "type")
            {
                if (!stockState.ContainsValue(e.DisplayText))
                {
                    int display = -100;
                    string disTxt = e.DisplayText;
                    try
                    {
                        display = Convert.ToInt32(e.DisplayText);
                        e.DisplayText = enumPandianType[display];
                    }
                    catch
                    {
                        return;
                    }
                }
            }
            else if (e.Column.FieldName == "createtime" 
                || e.Column.FieldName == "startTime"
                || e.Column.FieldName == "endTime" )
            {
                e.Column.DisplayFormat.FormatString = "yyyy-MM-dd HH:mm:ss";
            }
        }
       
        bool isDataSourceChanged = false;
        private void gridView1_DataSourceChanged(object sender, EventArgs e)
        {
            isDataSourceChanged = true;
            if (selectedRowIndex > 0 && dtPandian.Rows.Count > selectedRowIndex)
            {
                gridView1.FocusedRowHandle = selectedRowIndex;
                gridView1.MakeRowVisible(selectedRowIndex);
            }
            else
            {
                selectedRowIndex = 0;
            }
        }
        private void gridView1_FocusedRowObjectChanged(object sender, FocusedRowObjectChangedEventArgs e)
        {
            if (gridView1.FocusedRowHandle < 0 || gridView1.FocusedRowHandle == selectedRowIndex || isDataSourceChanged)
            {
                isDataSourceChanged = false;
                if (gridView1.IsGroupRow(e.RowHandle)) //set first row of group selected
                {
                    selectedRowIndex = gridView1.GetChildRowHandle(e.RowHandle, 0);
                  //  setCurrentRequestDetail();
                }
                setCurrentRequestDetail();
                return;
            }
            selectedRowIndex = gridView1.FocusedRowHandle;
            // showErrorMsg("selection:"+ selectedRowIndex);
      
            clearInputs();
            setCurrentRequestDetail();
        }
        private void clearInputs()
        {
           
        }
        private void setCurrentRequestDetail()
        {
            if (!getCurrentObject() || string.IsNullOrEmpty(currentOrderNo))
            {
                return;
            }
            showWaitForm();
            try
            {
              
             
                clearInputs();
     
             
            }
            catch (Exception e)
            {
                showErrorMsg(e,e.Message);
            }
            closeWaitForm();
        }
        private bool getCurrentObject()
        {
            btnDetail.Enabled  = btnDel.Enabled = btnStart.Enabled = false;
            if (selectedRowIndex < 0 || selectedRowIndex >= dtPandian.Rows.Count)
            {
                return false;
            }
            //  DataRow currentRow = dt.Rows[selectedRowIndex];
            DataRowView dr = (DataRowView)(GetGridViewFilteredAndSortedData(gridView1)[selectedRowIndex]);
            currentOrderNo = dr["orderNo"].ToString(); ;
            currentPandian = new WmsStockPandian(dr.Row);
            btnStart.Enabled = currentPandian.status == 0;
           btnDel.Enabled = btnStart.Enabled  ;
             btnPrint.Enabled= btnDetail.Enabled = true;
            return true;
        }
     
        private void btnQuery2_Click(object sender, EventArgs e)
        {
         
            query();
        }
        private void bbiExport_ItemClick(object sender, ItemClickEventArgs e)
        {
            exportExcel(gridView1);
        }
      
        private void btnAdd_Click(object sender, EventArgs e)
        {
           string conditionStr = "";
           string inputValues = "comboStkType:" + comboStkType.SelectedIndex + WmsConstants.SPLIT
                              + "txtGoodsId:" + txtGoodsId.Text + WmsConstants.SPLIT
                              + "comboBoPart:" + comboBoPart.SelectedIndex + WmsConstants.SPLIT
                              + "comboBoGoodsType:" + comboBoGoodsType.SelectedIndex + WmsConstants.SPLIT
                              + "txtGoodName:" + txtGoodName.Text + WmsConstants.SPLIT
                                + "combNotice:" + combNotice.SelectedIndex + WmsConstants.SPLIT
                            ;
            conditionStr += (this.comboStkType.SelectedIndex < 0 ? "" : string.Format("{0} = #{1};", WmsLocation.fields.whType.ToString(), ((Colitem)this.comboStkType.SelectedItem).key))
                        + (this.txtGoodsId.Text.Trim().Length == 0 ? "" : string.Format("{0} = # '{1}';", WmsStock.fields.goodsId.ToString(), filtRiskChar(txtGoodsId.Text.Trim())))
                       + (this.comboBoPart.SelectedIndex <= 0 ? "" : string.Format("{0} = #{1};", WmsLocation.fields.part.ToString() ,  ((Node)this.comboBoPart.SelectedItem).ID))
                     //   + (this.comboState.SelectedIndex < 0 ? "" : string.Format("{0} = #{1};", WmsLocation.fields.state.ToString(), ((Colitem)this.comboState.SelectedItem).key))
                        + (this.comboBoGoodsType.SelectedIndex <= 0 ? "" : string.Format("{0} = #{1};", WmsLocation.fields.goodsType.ToString(), ((Node)this.comboBoGoodsType.SelectedItem).ID))
                        + (this.txtGoodName.Text.Trim().Length == 0 ? "" : string.Format("{0} like # '%{1}%';", WmsGoods.exfields.goodsName.ToString(), filtRiskChar(txtGoodName.Text.Trim())))
                       //  + (this.txtPlanStartdate.Text.Trim().Length == 0 ? "" : string.Format("{0} like # '{1}%';", WmsStock.fields.productDate.ToString(), filtRiskChar(txtPlanStartdate.Text.Trim())))
                       // + (this.txtPlanEnddate.Text.Trim().Length == 0 ? "" : string.Format("{0} like # '{1}%';", WmsStock.fields.validDate.ToString(), filtRiskChar(txtPlanEnddate.Text.Trim())))
                        ;
           try
           {
               stkLocClient.createPandianOrder(((Colitem)this.comPType.SelectedItem).key, //combNotice.SelectedIndex == 1, 
                   this.comPType.SelectedIndex==2,
                   LoginInfo.UserId, inputValues, conditionStr) ;
               closeClient();
           }
           catch (Exception er)
           {
              
               closeWaitForm(); 
               closeClient();
               showErrorMsg(er, er.Message);
           }
           closeWaitForm();
           query();
        }
        private void btnStart_Click(object sender, EventArgs e)
        {
            if (currentPandian.status > 0)
            {
                showErrorMsg(currentPandian.orderNo + "已经开始盘点了");
                btnStart.Enabled = false;
                return;
            }
            if (!stkLocClient.canStartNewPandian())
            {
                showErrorMsg("请结束未完成的盘点。");
                return;
            }
            showWaitForm();
            try
            { 
 
                stkLocClient.startPandianOrder(currentOrderNo);
                closeClient();
                query();
            }
            catch (Exception er)
            {
                closeWaitForm();
                closeClient();
                showErrorMsg(er, er.Message);
            }
            closeWaitForm();
           
        }
        private void btnDel_Click(object sender, EventArgs e)
        {
            DialogResult r = MessageBox.Show(string.Format("确定要删除盘点单{0}吗 ?", currentPandian.orderNo),
                                       "确认删除", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
            if (r == DialogResult.No)
            {
                return;
            }
            showWaitForm();
            try
            { 
                stkLocClient.delPandianOrder(currentPandian.orderNo);
                closeClient();
                query();
            }
            catch (Exception er)
            {
                closeWaitForm();
                closeClient();
                showErrorMsg(er, er.Message);
            }
            closeWaitForm();
           
        }
        private void btnDetail_Click(object sender, EventArgs e)
        {
            showWaitForm();
            Form frm = ((main)this.ParentForm).getOpenedForm("盘点明细");
            StockPandianDetailForm spdf = frm == null? new StockPandianDetailForm() 
                                : (StockPandianDetailForm)((main)this.ParentForm).getOpenedForm("盘点明细");
            
             
            spdf.setPandianNo(currentOrderNo);
            if (frm == null)
            {
                if (this.ParentForm != null)
                {
                    ((main)this.ParentForm).OpenLink(spdf, "盘点明细");
                }
            }
            closeWaitForm();
        }
        private void btnPrint_Click(object sender, EventArgs e)
        {
            printPreOrder();
        }
        void printPreOrder(string preOrder = "")
        {
            if (String.IsNullOrEmpty(WmsConstants.PRINTER_NAME_PIN))
            {
                string msg = String.Format("没有定义多联打印机,请先设置多联打印机");
                showErrorMsg(msg);
                return;
            }
            if (string.IsNullOrEmpty(preOrder) && string.IsNullOrEmpty(currentOrderNo))
            {
                showErrorMsg("没有盘点单打印");
                return;
            }
            string toPrintNo = currentOrderNo;
            if (!string.IsNullOrEmpty(preOrder))
            {
                toPrintNo = preOrder;
            }
            showWaitForm();
            try
            { //只打印未完成收货的明细,一张预到可对应一个采购单的多次收货
                printIn.printPandianItemsMulti(toPrintNo);
            }
            catch (Exception er)
            {
                showErrorMsg(er);
            }
            closeWaitForm();
        }
        private void btnUpdate_Click(object sender, EventArgs e)
        {
        }
        private void gridControl1_Click(object sender, EventArgs e)
        {
        }
    }
}