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 DeiNiu.wms.win.ServiceReferenceNodes;
using DeiNiu.Utils;
using DevExpress.XtraEditors.Controls;
namespace DeiNiu.wms.win
{
    public partial class DictionaryForm : BasicRibbonForm
    {
        ServiceReferenceNodes.NodeClient client{
            get { return Park.client; }
        }
        wcfNode wnode = new wcfNode();
       // lNode lgt = new lNode(); 
        private string fieldName = Node.fields.name.ToString();
        private string fieldDesc =Node.fields.description.ToString();
        private string lastQuery = "";
        private DataTable dt;
        //private int selectedNodeValue =-1;
        private bool isAdding = true;
        private int parentId = 0;
        int lastEditId =-1;
        int lastParent = -1; //last deleted 's parent id
        DevExpress.XtraTreeList.Nodes.TreeListNode parentNode;
        public DictionaryForm()
        {
            InitializeComponent();
            initialControls();
            query();// queryWithNewThread();
            // This line of code is generated by Data Source Configuration Wizard
            loadDesks();
        }
      
        #region initialControls
        private void initialControls()
        {
            initialTreelist(); 
            initialQueryInput();
            swithOperationType();
            setValidationRule();
            txtParent.Properties.ReadOnly = true;
            comType.ReadOnly = true;
            txtID.Properties.ReadOnly = true;
            this.txtFlag.ReadOnly = !checkPermission(WmsConstants.SPECIAL_AUTHS_DIC_DELETE);
           // swSys.Enabled =  checkPermission(WmsConstants.SPECIAL_AUTHS_SUPER); 
            initialComboBoxes();
        }
        private void initialComboBoxes()
        {
            //initial combobox of port
            initialComboBoxs(comType, dicValueType, false);
            this.comType.Properties.TextEditStyle = TextEditStyles.DisableTextEditor;
            this.comType.SelectedIndex = 0;
        }
       
        private void setValidationRule()
        {
          dxValidationProvider1.ValidationMode = ValidationMode.Auto;
          dxValidationProvider1.SetValidationRule(txtDicName, ValidationRules.notEmptyValidationRule);
          txtDicName.Properties.MaxLength = 40;
          txtGoodDesc.Properties.MaxLength = 250;
          textEdit1.Properties.MaxLength = txtDicName.Properties.MaxLength;
         // txtFlag.Properties.MaxLength = 5;
          ConditionValidationRule rangeValidationRule = new ConditionValidationRule();
          rangeValidationRule.ConditionOperator = ConditionOperator.Between;
          rangeValidationRule.Value1 = 1;
          rangeValidationRule.Value2 = 10000;
          rangeValidationRule.ErrorText = String.Format("{0} - {1} 之间任意一数字!", 1000, 9999);
          rangeValidationRule.ErrorType = ErrorType.Critical;
       //   dxValidationProvider.SetValidationRule(txtFlag, rangeValidationRule);
         // dxValidationProvider.SetValidationRule(txtFlag, ValidationRules.getNumberRangeValidationRule(0,10000));
          txtFlag.Text = "0";
        }
        private void initialTreelist()
        {
            //this.treeList1.BorderStyle = DevExpress.XtraEditors.Controls.BorderStyles.NoBorder;
            //treeList1.OptionsView.ShowHorzLines = false;
            //treeList1.OptionsView.ShowVertLines = false;
            treeList1.FocusedNodeChanged += new DevExpress.XtraTreeList.FocusedNodeChangedEventHandler( treeList1_FocusedNodeChanged);
            treeList1.KeyFieldName = "id";
            treeList1.ParentFieldName = "parentid";
            treeList1.OptionsBehavior.Editable = false;
            //searchLookUpEdit1.Properties.ValueMember = "id";
            //searchLookUpEdit1.Properties.DisplayMember = fieldName;
            //searchLookUpEdit1.Properties.NullText = "系统";  
        }
        #endregion
        private void buildTreelist()
        { 
            Node nd = new Node();
            //dt = nd.Query().Tables[0];  
            //treeList1.DataSource = dt;
            string query = txtQuery.Text.Trim(); 
            lastQuery = query;
            try
            {
                dt = client.Query(query, 0, 0).Tables[0]; ;
                client.Close();
            }
            catch (Exception e)
            {
                showErrorMsg(e,e.Message);
            }
                treeList1.DataSource = dt;
            
            //DataView dv = nd.Query().Tables[0].DefaultView;
            //dv.RowFilter = "parentid =0";
            //searchLookUpEdit1.Properties.DataSource =dv ;
            setFocusedNode();
             
        }
         
        private void setFocusedNode()
        {          
            foreach (DevExpress.XtraTreeList.Nodes.TreeListNode node in treeList1.Nodes)
            {
              //  if (lastEditId >-1)
                {
                    if (Convert.ToInt32(node.GetValue("id").ToString()) == lastEditId)
                    {
                        treeList1.FocusedNode = node;
                        return;
                    }
                    if (traverseNodes(node))
                    {
                        return;
                    }
                }
                    
                //if (Convert.ToInt32(node.GetValue("id").ToString()) == parentId)
                //{
                //        node.ExpandAll();                   
                //}
             //   node.ExpandAll();  
              }
             
        }  
        private bool traverseNodes(DevExpress.XtraTreeList.Nodes.TreeListNode parentNode)
        {
            foreach (DevExpress.XtraTreeList.Nodes.TreeListNode node in parentNode.Nodes)
            {
                if (Convert.ToInt32( node.GetValue("id").ToString()) == lastEditId) //set focus to last add/updated
                {
                    treeList1.FocusedNode = node;
                    return true;
                }
                if (Convert.ToInt32(node.GetValue("id").ToString()) == lastParent) //set focus for last delete
                {
                  //  node.ExpandAll();
                    node.Expanded = true; // expand only sub nodes.
                    if (node.Nodes.Count > 0)
                    {
                        treeList1.FocusedNode = node.Nodes[0];
                    }
                    else
                    {
                        treeList1.FocusedNode = node;
                    }
                }
                traverseNodes(node);
            }
            return false;
        }
        private void initialQueryInput()
        {
            this.txtQuery.KeyDown += new System.Windows.Forms.KeyEventHandler(this.txtQuery_KeyDown);
        }
        
      
        ///   
        /// loading data
        ///   
        private void loadData()
        {
            //this.gridviewGoodsType.DataSource = lgt.GetAllActiveData().Tables[0].DefaultView;
           
            string query = txtQuery.Text.Trim(); 
            lastQuery = query;
            try
            {
                DataSet ds = client.Query(query, 0, 0);
                client.Close();
                dt = ds.Tables[0];
            }
            catch (Exception e)
            {
                showErrorMsg(e.Message);
            }
          
             
        }
         
        private void btnNew_Click(object sender, EventArgs e)
        {
            /*
            if (lgt.getNode.ID > 0)
            {
                lgt.Initialize();
                clearInputs();
                txtGoodType.Focus();
                validData();
                return;
            }
            */
            // begin to create new goodType
           
            if (!validData())
            {
                return;
            }
            
            // lgt.initialize();
             setDataBack();  
         
            //Thread th = new Thread(new ThreadStart(this.newGoodType));
            //th.Start();
            btnNew.Enabled = false;
            newDic();
        }
        private void newDic()
        {         
            
            showWaitForm();  
            try
            {
             
                wnode = client.newWcfNode(wnode); applyDic();
                client.Close();
                
                lastEditId = wnode.id;
           //     lastEditId = lgt.getNode.ID;
                query();// loadData();   
                // initialize and clear object and inputs, prepare for adding more. 
               //lgt.initialize();
                clearInputs();
            }
            catch (Exception e)
            {
               showErrorMsg(e.Message);
            }
            finally
            {
               // WaitFormService.Close();
                closeWaitForm(); 
                btnNew.Enabled = true;
            } 
           
        }
      
        //private void bindDetail()
        //{
        //    //txtGoodDesc.Text = lgt.getNode.description;
        //    //txtGoodType.Text = lgt.getNode.name;
        //    txtGoodDesc.Text = wnode.description;
        //    txtDicName.Text = wnode.name;
        //    txtValue.Text = wnode.value;
        //    sw.IsOn = wnode.isOn;
        //    comType.SelectedIndex = wnode.valueType;
        //}
        private void setDataBack()
        {
            setParentInfo();
            wnode.parentid =   wnode.parentid > 0 ? wnode.parentid : parentId;
            wnode.description = txtGoodDesc.Text.Trim();
            wnode.name = txtDicName.Text.Trim();
            wnode.isOn = sw.IsOn;
            wnode.value = txtValue.Text.Trim();
            wnode.valueType = comType.SelectedIndex;
            wnode.isSystem = swSys.IsOn;
            if((enumDicValueType) comType.SelectedIndex ==  enumDicValueType.布尔) {
                wnode.value = sw.IsOn ? "开" : "关";
            }
            
            //lgt.getNode.parentid = lgt.getNode.parentid> 0 ? lgt.getNode.parentid :  parentId;
            //lgt.getNode.description = txtGoodDesc.Text.Trim();
            //lgt.getNode.name = txtGoodType.Text.Trim();
          //  lgt.getNode.operater = Park.currentUser.GetEmployee.ID;
            if (txtFlag.Text.Trim().Length > 0)
            {
                try
                {
                    int flag = Convert.ToInt16(txtFlag.Text.ToString());
                    wnode.flag = flag;
                }
                catch(Exception er)
                {
                    showErrorMsg(er.Message);
                    txtFlag.Focus();
                }
                
            }
        
          
        }
        void setParentInfo()
        {
            if (treeList1.FocusedNode == null)
            {
                parentId = 0;
                return;
            }
            btnNew.Enabled = false;
            if (parentNode == null || parentNode.ParentNode == null)
            {  // current is level 1,2
                parentId = Convert.ToInt32(this.treeList1.FocusedNode.GetValue("id").ToString());
                this.txtParent.Text = this.treeList1.FocusedNode.GetValue("name").ToString();
                 if (checkPermission(WmsConstants.SPECIAL_AUTHS_DIC_DELETE))
                {
                    comType.ReadOnly = false;
                    btnNew.Enabled = true;
                }
            }
            else if (parentNode != null)
            {
                if (parentNode.ParentNode != null)
                { //level 3, as max level
                     
                    parentId = Convert.ToInt32(this.treeList1.FocusedNode.GetValue("parentid").ToString());
                    this.txtParent.Text = parentNode.GetValue("name").ToString();
                    comType.ReadOnly = true;
                    btnNew.Enabled = true;
                    comType.SelectedIndex =string.IsNullOrEmpty(parentNode.GetValue("valueType").ToString())? 0 :  Convert.ToInt32( parentNode.GetValue("valueType").ToString());
                }
            }
        }
        private bool validData()
        {
            enumDicValueType type = (enumDicValueType)comType.SelectedIndex;
            try
            {
                switch (type)
                {
                    case enumDicValueType.浮点:
                        Convert.ToDecimal(txtValue.Text.Trim());
                        break;
                    case enumDicValueType.整型:
                        Convert.ToInt32(txtValue.Text.Trim());
                        break;
                }
            }
            catch
            {
                showErrorMsg("请输入正确的数字");
                txtValue.SelectAll();
                txtValue.Focus();
                return false;
            }
            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 void btnSave_Click(object sender, EventArgs e)
        {
            //if (!getCurrentObject())
            //{
            //    return;
            //}
            if (!validData())
            {
                return;
            }
            if (wnode.name.Equals(txtDicName.Text.Trim())
                && wnode.description.Equals(txtGoodDesc.Text.Trim())
                && wnode.flag == Convert.ToInt32(txtFlag.Text.Trim())
                && wnode.isOn == sw.IsOn
                && wnode.isSystem == swSys.IsOn 
                && wnode.value.Equals(txtValue.Text.Trim())
                && wnode.valueType.Equals(comType.SelectedIndex)
                )
            {
                MessageBox.Show("没有数据需要更新");
                return;
            }
         
            //Thread th = new Thread(new ThreadStart(this.updateGoodType));
            //th.Start();
             
            
            updateDic();
        }
        private void updateDic()
        {
            
            if (!checkPermission(WmsConstants.SPECIAL_AUTHS_DIC_UPDATE))
            {
                showErrorMsg(null,"权限不足!");
                return;
            }
            if (swSys.IsOn && !isSuper())
            {
                showErrorMsg(null, "权限不足!");
                return;
            }
            btnSave.Enabled = false;
            showWaitForm();
            //WaitFormService.Show(this);
            try
            {
                //update the goodtype 
                setDataBack();
               // lgt.getNode.Update();
              //  lgt.getNode.Update();
                
                client.updateWcfNode(wnode);
                applyDic();
                client.Close();
                lastEditId = wnode.id;
                //get updated data 
                query();// loadData();
            }
            catch (Exception e)
            {
                showErrorMsg(e,e.Message);
                getCurrentObject();
            }
            finally
            {
               // WaitFormService.Close();
                closeWaitForm();  
                btnSave.Enabled = true;
            }
         
         
        }
        void applyDic()
        {
            if (chkApply.Checked)
            {
                Park.getDictionary(true);
                client.applyDicChanges();
                Park.loadConfig();
                Park.getDictionary(true);
            }
        }
      
       
        private void clearInputs()
        {
            txtValue.Text = "";
          //  sw.IsOn = false;
          //  comType.SelectedIndex = 0;
            txtDicName.Text = "";
            txtGoodDesc.Text = "";
            txtID.Text = "";
            txtFlag.Text = "";
            dxValidationProvider1.RemoveControlError(txtFlag);
            dxValidationProvider1.RemoveControlError(txtDicName);
            wnode = new wcfNode();
        }
        private bool getCurrentObject()
        {
            //if (selectedNodeValue < 0)// || dt.Rows.Count <= selectedNodeValue)
            //{
            //    MessageBox.Show("请在列表里选择数据");
            //    return false;
            //} 
            DataRowView drv = treeList1.GetDataRecordByNode(this.treeList1.FocusedNode) as DataRowView;
            // lgt.getNode.getModel(drv.Row);
            Node nd = new Node(drv.Row);
            initialWcfNode(nd);
           // lgt.initialize(drv.Row);
          
            return true;
        }
        void initialWcfNode(Node nd)
        {
           
            wnode.id = nd.ID;
            wnode.name = nd.name;
            wnode.description = nd.description;
            wnode.parentid = nd.parentid;
            wnode.value = nd.value;
            wnode.valueType = nd.valueType;
            wnode.flag = nd.flag;
            wnode.isSystem = nd.isSystem;
            wnode.isOn = nd.isOn;
        }
        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (!getCurrentObject())
            {
                return;
            }
            if (!checkPermission(WmsConstants.SPECIAL_AUTHS_DIC_DELETE))
            {
                showErrorMsg("权限不足!");
                return;
            }
            if (swSys.IsOn && !isSuper())
            {
                showErrorMsg(null, "权限不足!");
                return;
            }
            MessageBoxButtons messButton = MessageBoxButtons.OKCancel;
            DialogResult dr = MessageBox.Show(String.Format("确定要删除 {0} 吗?",wnode.name), "删除记录", messButton);
            if (dr == DialogResult.OK)
            {
                parentId =  Convert.ToInt32(treeList1.FocusedNode .GetValue("parentid").ToString());
                try
                {
                   
                    client.deleteNode(wnode.id) ;
                    applyDic();
                    client.Close();
                    
                }
                catch (Exception er)
                {
                   showErrorMsg(er,er.Message);
                    return;
                }
              //  lgt.initialize();
                wnode = new wcfNode();
                lastEditId = -1;
                lastParent = parentId;
                query();//loadData();
            }
  
        }
        protected void query()
        {
            buildTreelist(); //bind tree  
            showAdminButtons();
        }
        private void showAdminButtons()
        {
            bool isShow = (checkPermission(WmsConstants.SPECIAL_AUTHS_DIC_DELETE));
            btnRestDesk.Enabled = isShow;
            btnPrintBox.Enabled = isShow;
        }
        private void btnQuery_Click(object sender, EventArgs e)
        {
            queryWithNewThread();
        }
        private void queryWithNewThread()
        {
            //Thread th = new Thread(new ThreadStart(this.queryGoodType));
            //th.Start();
            btnQuery.Enabled = false;
            queryGoodType();
        }
        private void queryGoodType()
        {
          
            showWaitForm();
            try
            { 
                query();// loadData();  
            }
            catch (Exception e)
            {
                showErrorMsg(e,e.Message);
            }
            finally
            {
                // WaitFormService.Close();
                closeWaitForm();
                btnQuery.Enabled = true;
            }
        }
      
 
        private void txtQuery_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 13)
            {
                query();
            }
        }
       
        private void treeList1_FocusedNodeChanged(object sender, DevExpress.XtraTreeList.FocusedNodeChangedEventArgs e)
        {
            clearInputs();
            DevExpress.XtraTreeList.Nodes.TreeListNode currentNode = treeList1.FocusedNode;
            if (currentNode == null)
            {
                return;
            } 
            parentNode = treeList1.FocusedNode.ParentNode;
            if (parentNode == null) //set root expand
            {
                treeList1.FocusedNode.Expanded = true;
            }
           this.txtParent.Text = parentNode == null ? "" : parentNode.GetDisplayText("name");
           setParentInfo();
      //     if (currentNode.Tag == null)
         //  {
               //string a = currentNode.GetValue("id").ToString();
               //selectedNodeValue = Convert.ToInt32(a);
               //DataView dv = dt.DefaultView;
               //dv.Sort = "id desc";
               //DataRowView[] drs = dv.FindRows(selectedNodeValue);
               //if (drs.Length > 0)
               //{
               //    DataRow dr = drs[0].Row;
               //    lgt.getNode.getModel(dr);
               //    currentNode.Tag = lgt.getNode;
               //}
              
             // currentNode.Tag = lgt.getNode; 
          // }
           getCurrentObject();
            if (isAdding)
            {
                return;
            }
            //txtGoodType.Text = currentNode.GetDisplayText(fieldName);
            //txtGoodDesc.Text = currentNode.GetDisplayText(fieldDesc);
            txtDicName.Text =wnode.name;
            txtGoodDesc.Text = wnode.description;
            txtFlag.Text = wnode.flag + "";
            txtID.Text = wnode.id > 0 ? wnode.id + "" : "";
            txtValue.Text = wnode.value;
            sw.IsOn = wnode.isOn;
            swSys.IsOn = wnode.isSystem;
            comType.SelectedIndex = wnode.valueType;
            txtDicName.Enabled = !swSys.IsOn || swSys.IsOn && isSuper();
            txtGoodDesc.Enabled = txtDicName.Enabled;
            txtFlag.Enabled = txtDicName.Enabled;
            txtValue.Enabled = txtDicName.Enabled;
            sw.Enabled = txtDicName.Enabled;
         //   comType.SelectedIndex = wnode.valueType;
            btnDelete.Enabled = treeList1.FocusedNode.Nodes.Count == 0;
            setParentInfo();
        }
        
        private void DictionaryForm_FormClosing(object sender, FormClosingEventArgs e)
        {
          //  client.Close();
        }
        private void comType_SelectedIndexChanged(object sender, EventArgs e)
        {
            lcBool.Visibility = comType.SelectedIndex ==(int)enumDicValueType.布尔 ?  DevExpress.XtraLayout.Utils.LayoutVisibility.Always : DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
            lcValue.Visibility = comType.SelectedIndex == (int)enumDicValueType.布尔 ? DevExpress.XtraLayout.Utils.LayoutVisibility.Never : DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
            
        }
        private void btnRestDesk_Click(object sender, EventArgs e)
        {
            using (ServiceReferenceSetup.SetupClient client = new ServiceReferenceSetup.SetupClient("BasicHttpBinding_ISetup", buildSvrAddress("Setup.svc")))
            {
                try
                {
                    if (client.initialDesk())
                    {
                        MessageBox.Show("复合台初始化成功!");
                    }
                }
                catch (Exception er)
                {
                    showErrorMsg(er, er.Message);
                }
            }
        }
        private void loadDesks()
        {
            using (ServiceReferenceSetup.SetupClient client = new ServiceReferenceSetup.SetupClient("BasicHttpBinding_ISetup", buildSvrAddress("Setup.svc")))
            {
                try
                {
                    DataTable dt = client.getDesks();
                    List desks = new List();
                    foreach (DataRow dr in dt.Rows)
                    { 
                        desks.Add(enumColors[Convert.ToInt16(dr["name"].ToString().Trim())]);
                    }
                    initialComboBoxs(this.comboxColors, desks.ToArray(), "全部"); 
                }
                catch (Exception er)
                {
                    showErrorMsg(er, er.Message);
                }
            }
        }
        private void btnPrintBox_Click(object sender, EventArgs e)
        {
        }
        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            swithOperationType();
        }
        private void swithOperationType()
        {
            isAdding = tabFuncs.SelectedTabPageIndex ==1;
            if (isAdding)
            {
                clearInputs();
            }
            else
            {
                treeList1_FocusedNodeChanged(null, null);
            }
            btnNew.Enabled = isAdding;
            btnSave.Enabled = !isAdding;
            btnDelete.Enabled = !isAdding;
            if (treeList1.FocusedNode != null)
            {
                btnDelete.Enabled = btnDelete.Enabled && treeList1.FocusedNode.Nodes.Count == 0;
            }
        }
        private void tabbedControlGroup3_SelectedPageChanged(object sender, DevExpress.XtraLayout.LayoutTabPageChangedEventArgs e)
        {
            swithOperationType();
        }
        
    }
}