using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Windows.Forms; using DevExpress.XtraGrid.Columns; using DevExpress.XtraGrid.Views.Grid; using DevExpress.XtraTreeList; using DevExpress.XtraTreeList.Nodes; using Lskj.Business; using Lskj.Business.Impl; using Lskj.Control; using Lskj.Control.Model; using Lskj.Core; using Lskj.Main.Model; using Lskj.Model; using Lskj.Util; namespace Lskj.PubCodeDesign { public partial class FrmMain : Form { private const string NodeTypeMenu = "menu"; private const string NodeTypeScheme = "scheme"; private const string ExecTypeView = "0"; private const string ExecTypeDesign = "1"; private const int MenuStructStepLength = 2; private const int LeafTreeLevel = 3; private const int MaxMenuStructLevel = 2; private const int DesignFieldControlWidth = 160; private const int DesignFieldControlHeight = 28; private const string SplitRootLocationKeyFormat = "code_design_left_width_{0}"; private const string SchemeTableName = "P_CodeSchemeTab"; private const string SchemeControlTableName = "P_CodeSchemeControlTab"; private const string CodeRecordTableName = "P_CodeSchemeRecordTab"; private const string CodeGenerateProcedureName = "P_create_CodeSchemeDocumentPr"; private const string NumberRuleTableName = "p_systemNumberRuleTab"; private const string DesignRuleUseColumn = "UseEd"; private const string DesignRuleSortColumn = "SortNo"; private const string DesignRuleUserNameColumn = "UserName"; private const string DesignRuleFieldNameColumn = "FieldName"; private const string DesignRuleFieldTypeColumn = "FieldTypeId"; private const string NumberRuleSchemeIdColumn = "SchemeId"; private const string NumberRuleSchemeCodeColumn = "SchemeCode"; private const string NumberRuleSchemeNameColumn = "SchemeName"; private const string NumberRuleMenuKeyColumn = "MenuKey"; private const string NumberRuleBindModuleColumn = "BindModule"; private const string NumberRuleBindModuleCodeColumn = "BindModuleCode"; private const string NumberRuleModIdColumn = "modid"; private const string NumberRuleSourceTableProperty = "NumberRuleSourceTable"; public DynamicCodeDesign Model; // 动态编码设计对象 private DataTable _allMenus = new DataTable(); private DataTable _fieldConfigTable = new DataTable(); private DataTable _designRuleTable = new DataTable(); private DataTable _moduleLeftSourceTable = new DataTable(); private readonly List _viewSchemeItems = new List(); private DataRow _moduleLeftSourceRow; private DataRow _menuTreeSourceRow; private string _menuTreeKeyField; private string _menuTreeTextField; private string _menuTreeNodeLength; private string _menuSql; private string _currentSchemeKey; private TreeListNode _currentSchemeNode; private int _treeIconSerial; private bool _loadingSplitLocation; private bool _currentSchemeDirty; private bool _loadingSchemeEditor; private bool _loadingBindControls; private bool _loadingDesignRuleGrid; private bool _restoringFocusedNode; private bool _suppressNextFocusPrompt; private bool _numberRuleGridInitialized; private string _numberRuleGridModuleCode; private MyControl _viewControlObj; public FrmMain() { InitializeComponent(); InitializeRuntimeEvents(); this.Load += OnFrmMainLoad; } private void OnFrmMainLoad(object sender, EventArgs e) { CodeSchemeStorage.EnsureCodeSchemeStorage(); InitlizeSpiltLocation(); LoadTreeIcons(); LoadMenuTree(); InitializeNumberRuleGridWithPrompt(); ApplyExecMode(); } protected override void OnFormClosing(FormClosingEventArgs e) { CommitDesignRuleGridEditor(); bool canClose = ConfirmAbandonCurrentSchemeChanges(); SetMainModuleCloseState(canClose); if (!canClose) { e.Cancel = true; return; } base.OnFormClosing(e); } private void SetMainModuleCloseState(bool isClose) { string guid = this.Tag + ""; if (string.IsNullOrWhiteSpace(guid)) return; try { if (Manager.ModuleForms.ContainsKey(guid)) { Manager.ModuleForms[guid].IsClose = isClose; } } catch { } } private void InitializeRuntimeEvents() { this.splitRoot.SplitterMoved += OnSplitterMoved; this.treeMenu.MouseDown += OnTreeMenuMouseDown; this.treeMenu.BeforeFocusNode += OnTreeMenuBeforeFocusNode; this.treeMenu.FocusedNodeChanged += OnTreeMenuFocusedNodeChanged; this.menuAddScheme.Click += OnAddSchemeClick; this.btnDeleteScheme.Click += OnDeleteSchemeClick; this.btnGenerateCode.Click += OnGenerateCodeClick; this.btnAddLogic.Click += OnAddLogicClick; this.btnDeleteLogic.Click += OnDeleteLogicClick; this.btnSave.Click += OnSaveSchemeClick; this.txtSchemeName.KeyDown += OnSchemeNameKeyDown; this.txtSchemeName.EditValueChanged += OnSchemeNameChanged; this.pl_buttom.Resize += OnBottomPanelResize; InitializeDesignRuleGridControl(); InitializeBindModuleEvents(); LayoutBottomButtons(); SetSchemeEditor(null); } private bool IsViewMode() { string execType = this.Model == null ? ExecTypeDesign : (this.Model.ExecType + "").Trim(); return string.Equals(execType, ExecTypeView, StringComparison.OrdinalIgnoreCase); } private bool IsDesignMode() { return !IsViewMode(); } private void ApplyExecMode() { bool designMode = IsDesignMode(); this.menuAddScheme.Visible = designMode; this.cmsMenuTree.Enabled = designMode; this.btnDeleteScheme.Visible = designMode; this.btnGenerateCode.Visible = !designMode; this.btnAddLogic.Visible = designMode; this.btnDeleteLogic.Visible = designMode; this.btnSave.Visible = designMode; this.pl_buttom.Visible = designMode; this.pnlDesignWork.Visible = true; this.pnlViewWork.Visible = false; this.lblCodePreview.Visible = !designMode; this.txtCodePreview.Visible = !designMode; this.txtCodePreview.Properties.ReadOnly = true; SetSchemeEditor(this._currentSchemeNode == null ? null : this._currentSchemeNode.Tag as TreeNodeData); ApplyDesignRuleGridEditState(); } private void InitializeDesignRuleGridControl() { this.gridDesignRules.VisibleOperPanel = false; this.gridDesignRules.VisibleSearchPanel = true; this.gridDesignRules.HideTopToolPanel(); } private void OnBottomPanelResize(object sender, EventArgs e) { LayoutBottomButtons(); } private void LayoutBottomButtons() { if (this.pl_buttom == null || this.btnAddLogic == null || this.btnDeleteLogic == null || this.btnSave == null) return; const int marginRight = 8; const int gap = 6; int top = Math.Max(4, (this.pl_buttom.Height - this.btnSave.Height) / 2); this.btnSave.Top = top; this.btnDeleteLogic.Top = top; this.btnAddLogic.Top = top; this.btnSave.Left = Math.Max(6, this.pl_buttom.ClientSize.Width - marginRight - this.btnSave.Width); this.btnDeleteLogic.Left = this.btnSave.Left - gap - this.btnDeleteLogic.Width; this.btnAddLogic.Left = this.btnDeleteLogic.Left - gap - this.btnAddLogic.Width; if (this.btnAddLogic.Left < 6) { this.btnAddLogic.Left = 6; this.btnDeleteLogic.Left = this.btnAddLogic.Right + gap; this.btnSave.Left = this.btnDeleteLogic.Right + gap; } } private GridControlEx DesignRuleGrid { get { return this.gridDesignRules == null ? null : this.gridDesignRules.GridControlObj; } } private void InitializeBindModuleEvents() { this.chkBindModule.CheckedChanged += OnBindModuleCheckedChanged; this.cboBindLevel1.SelectedIndexChanged += OnBindLevel1Changed; this.cboBindLevel2.SelectedIndexChanged += OnBindLevel2Changed; this.cboBindLevel3.SelectedIndexChanged += OnBindLevel3Changed; } private void InitlizeSpiltLocation() { this._loadingSplitLocation = true; try { ApplySavedSplitLocation(this.splitRoot, GetSplitLocationKey(SplitRootLocationKeyFormat)); } catch (Exception ex) { LogHelper.Instance.WriteError(ex); } finally { this._loadingSplitLocation = false; } } private void ApplySavedSplitLocation(DevExpress.XtraEditors.SplitContainerControl splitControl, string key) { if (splitControl == null || string.IsNullOrWhiteSpace(key)) return; string value = IniHelper.Read(key); int splitterPosition; if (!int.TryParse(value, out splitterPosition) || splitterPosition <= 0) return; splitControl.SplitterPosition = NormalizeSplitterPosition(splitControl, splitterPosition); } private void OnSplitterMoved(object sender, EventArgs e) { if (this._loadingSplitLocation) return; try { if (sender == this.splitRoot) { IniHelper.Write(GetSplitLocationKey(SplitRootLocationKeyFormat), this.splitRoot.SplitterPosition + ""); } } catch (Exception ex) { LogHelper.Instance.WriteError(ex); } } private int NormalizeSplitterPosition(DevExpress.XtraEditors.SplitContainerControl splitControl, int splitterPosition) { if (splitControl == null) return splitterPosition; int length = Math.Max(splitControl.Width, splitControl.Height); if (length <= 0) return splitterPosition; const int minPanelLength = 80; int maxPosition = Math.Max(minPanelLength, length - minPanelLength); return Math.Max(minPanelLength, Math.Min(maxPosition, splitterPosition)); } private string GetSplitLocationKey(string keyFormat) { return string.Format(keyFormat, GetSplitLocationModuleCode()); } private string GetSplitLocationModuleCode() { if (this.Model != null && !string.IsNullOrWhiteSpace(this.Model.ModuleCode)) { return this.Model.ModuleCode; } return "Lskj.PubCodeDesign"; } private void LoadTreeIcons() { this.imgMenuTree.Images.Clear(); string iconPath = PubUtil.MainTreeviewImagePath; if (Directory.Exists(iconPath)) { string[] files = Directory.GetFiles(iconPath, "*.png").OrderBy(n => n).ToArray(); foreach (string file in files) { using (Image image = ImageHelper.ReadImage(file)) { if (image != null) { this.imgMenuTree.Images.Add(new Bitmap(image)); } } } } if (this.imgMenuTree.Images.Count == 0) { this.imgMenuTree.Images.Add(new Bitmap(18, 18)); } } private int GetNextTreeIconIndex() { int iconCount = this.imgMenuTree.Images.Count; if (iconCount == 0) return 0; int iconIndex = Math.Abs(this._treeIconSerial) % iconCount; this._treeIconSerial++; return iconIndex; } private void LoadMenuTree() { this.treeMenu.BeginUpdate(); try { this.treeMenu.Nodes.Clear(); this._treeIconSerial = 0; LoadBindMenuSource(); DataTable speciesTreeTable = LoadSpeciesTreeTable(); BindSpeciesTree(speciesTreeTable); LoadBindLevel1Items(null); if (this.treeMenu.Nodes.Count > 0) { this.treeMenu.CollapseAll(); this.lblDesignerStatus.Text = "右键编码分类可添加方案"; } else { this.lblDesignerStatus.Text = "未获取到可展示的编码分类数据"; } } catch (Exception ex) { this.lblDesignerStatus.Text = "编码分类加载失败"; MessageUtil.Show("编码分类加载失败:" + ex.Message); } finally { this.treeMenu.EndUpdate(); } } private void BindMenuTree(DataTable menuTable, List topSubSystems) { if (menuTable == null || menuTable.Rows.Count == 0 || !menuTable.Columns.Contains("MenuStruct")) return; if (topSubSystems == null || topSubSystems.Count == 0) return; HashSet visibleSubSysIds = new HashSet(topSubSystems.Select(n => n["SubSysId"] + "")); List rows = menuTable.Rows.Cast() .Where(IsMenuTreeRow) .Where(n => visibleSubSysIds.Contains(GetRowValue(n, "SubSysId"))) .OrderBy(n => GetTopSubSystemSortIndex(topSubSystems, GetRowValue(n, "SubSysId"))) .ThenBy(n => n["MenuStruct"] + "") .ThenBy(n => n.Table.Columns.Contains("MenuId") ? n["MenuId"] + "" : "") .ToList(); Dictionary nodeMap = new Dictionary(); foreach (DataRow subSystemRow in topSubSystems) { string topNodeKey = GetTopNodeKey(subSystemRow); if (nodeMap.ContainsKey(topNodeKey)) continue; TreeListNode topNode = AppendTreeNode(null, GetTopNodeText(subSystemRow), new TreeNodeData { NodeType = NodeTypeMenu, MenuKey = topNodeKey, MenuLevel = 1 }, GetNextTreeIconIndex()); nodeMap.Add(topNodeKey, topNode); } foreach (DataRow row in rows.Where(n => GetMenuLevel(n["MenuStruct"] + "") == 1)) { string nodeKey = GetMenuNodeKey(row); if (nodeMap.ContainsKey(nodeKey)) continue; TreeListNode node = AppendTreeNode(nodeMap[GetTopNodeKey(row)], GetMenuNodeText(row), new TreeNodeData { NodeType = NodeTypeMenu, MenuKey = nodeKey, MenuLevel = 2, MenuRow = row }, GetNextTreeIconIndex()); nodeMap.Add(nodeKey, node); } foreach (DataRow row in rows.Where(n => GetMenuLevel(n["MenuStruct"] + "") == MaxMenuStructLevel)) { string nodeKey = GetMenuNodeKey(row); string parentKey = GetMenuParentNodeKey(row); if (nodeMap.ContainsKey(nodeKey) || string.IsNullOrEmpty(parentKey) || !nodeMap.ContainsKey(parentKey)) continue; TreeListNode node = AppendTreeNode(nodeMap[parentKey], GetMenuNodeText(row), new TreeNodeData { NodeType = NodeTypeMenu, MenuKey = nodeKey, MenuLevel = LeafTreeLevel, MenuRow = row }, GetNextTreeIconIndex()); nodeMap.Add(nodeKey, node); } AppendCodeSchemeNodes(nodeMap); } private void AppendCodeSchemeNodes(Dictionary nodeMap) { if (nodeMap == null || nodeMap.Count == 0) return; DataTable table = GetCodeSchemes(); int schemeIconIndex = Math.Min(3, this.imgMenuTree.Images.Count - 1); foreach (DataRow row in table.Rows) { string menuKey = row["MenuKey"] + ""; if (!nodeMap.ContainsKey(menuKey)) continue; TreeListNode menuNode = nodeMap[menuKey]; TreeNodeData menuData = menuNode.Tag as TreeNodeData; TreeListNode schemeNode = AppendTreeNode(menuNode, row["SchemeName"] + "", new TreeNodeData { NodeType = NodeTypeScheme, MenuKey = menuKey, MenuRow = menuData == null ? null : menuData.MenuRow, MenuCaption = menuData == null ? string.Empty : menuData.MenuCaption, ModuleCode = menuData == null ? string.Empty : menuData.ModuleCode, SchemeId = ToInt(row["SchemeId"]), SchemeCode = row["SchemeCode"] + "", SchemeName = row["SchemeName"] + "", BindModule = ToBool(GetRowValue(row, "BindModule")), BindSubSysId = GetRowValue(row, "BindSubSysId"), BindMenuStruct1 = GetRowValue(row, "BindMenuStruct1"), BindMenuStruct2 = GetRowValue(row, "BindMenuStruct2"), BindMenuId = GetRowValue(row, "BindMenuId"), BindModuleCode = GetRowValue(row, "BindModuleCode") }, schemeIconIndex); } } private TreeListNode AppendTreeNode(TreeListNode parentNode, string text, TreeNodeData nodeData, int iconIndex) { TreeListNode node = this.treeMenu.AppendNode(new object[] { text }, parentNode); node.Tag = nodeData; node.ImageIndex = iconIndex; node.SelectImageIndex = iconIndex; return node; } private List GetVisibleTopSubSystems(DataTable menuTable) { List result = new List(); if (menuTable == null || menuTable.Rows.Count == 0) return result; string where = string.IsNullOrEmpty(ERPInfo.Instance.SeriesId) ? "" : string.Format("and SeriesId={0}", ERPInfo.Instance.SeriesId); DataTable subSystems = MainImpl.GetSubSystems(where); if (LanguageTranslation.Translatable) { subSystems = LanguageTranslation.TranslationTableColumn(subSystems, "SubSysName"); } foreach (DataRow subSystemRow in subSystems.Rows) { if (!string.Equals(GetRowValue(subSystemRow, "UseEd"), "True", StringComparison.OrdinalIgnoreCase)) continue; string subSysId = GetRowValue(subSystemRow, "SubSysId"); if (string.IsNullOrWhiteSpace(subSysId)) continue; if (HasVisibleMenu(menuTable, subSysId)) { result.Add(subSystemRow); } } return result; } private bool HasVisibleMenu(DataTable menuTable, string subSysId) { List parentMenus = menuTable.Rows.Cast() .Where(IsMenuTreeRow) .Where(n => GetMenuLevel(n["MenuStruct"] + "") == 1) .Where(n => string.Equals(GetRowValue(n, "SubSysId"), subSysId, StringComparison.OrdinalIgnoreCase)) .Where(n => !IsSplitBarMenu(n)) .ToList(); foreach (DataRow parentMenu in parentMenus) { string menuStruct = parentMenu["MenuStruct"] + ""; bool hasChild = menuTable.Rows.Cast() .Where(IsMenuTreeRow) .Any(n => GetMenuLevel(n["MenuStruct"] + "") == MaxMenuStructLevel && string.Equals(GetRowValue(n, "SubSysId"), subSysId, StringComparison.OrdinalIgnoreCase) && (n["MenuStruct"] + "").StartsWith(menuStruct) && !IsSplitBarMenu(n) && !string.IsNullOrWhiteSpace(GetRowValue(n, "DllFileName"))); if (hasChild) return true; } return false; } private bool IsSplitBarMenu(DataRow row) { string splitBar = SystemInfo.Instance.SplitBar; return !string.IsNullOrWhiteSpace(splitBar) && GetMenuNodeText(row).StartsWith(splitBar); } private int GetTopSubSystemSortIndex(List topSubSystems, string subSysId) { for (int i = 0; i < topSubSystems.Count; i++) { if (string.Equals(GetRowValue(topSubSystems[i], "SubSysId"), subSysId, StringComparison.OrdinalIgnoreCase)) { return i; } } return int.MaxValue; } private bool IsMenuTreeRow(DataRow row) { if (row == null || !row.Table.Columns.Contains("MenuStruct")) return false; string menuStruct = row["MenuStruct"] + ""; if (string.IsNullOrWhiteSpace(menuStruct)) return false; if (menuStruct.Length % MenuStructStepLength != 0) return false; int level = GetMenuLevel(menuStruct); return level > 0 && level <= MaxMenuStructLevel; } private int GetMenuLevel(string menuStruct) { return string.IsNullOrEmpty(menuStruct) ? 0 : menuStruct.Length / MenuStructStepLength; } private string GetMenuNodeKey(DataRow row) { string subSysId = GetRowValue(row, "SubSysId"); string nodeKey = string.Format("{0}|{1}", subSysId, row["MenuStruct"]); if (GetMenuLevel(row["MenuStruct"] + "") == MaxMenuStructLevel) { string menuId = GetRowValue(row, "MenuId"); if (!string.IsNullOrWhiteSpace(menuId)) { nodeKey = string.Format("{0}|{1}", nodeKey, menuId); } } return nodeKey; } private string GetTopNodeKey(DataRow row) { string subSysId = GetRowValue(row, "SubSysId"); return "top|" + subSysId; } private string GetMenuParentNodeKey(DataRow row) { string menuStruct = row["MenuStruct"] + ""; if (menuStruct.Length <= MenuStructStepLength) return GetTopNodeKey(row); string parentStruct = menuStruct.Substring(0, menuStruct.Length - MenuStructStepLength); string subSysId = GetRowValue(row, "SubSysId"); return string.Format("{0}|{1}", subSysId, parentStruct); } private string GetTopNodeText(DataRow row) { string subSysName = GetRowValue(row, "SubSysName"); if (!string.IsNullOrWhiteSpace(subSysName)) return subSysName; string subSysId = GetRowValue(row, "SubSysId"); return string.IsNullOrWhiteSpace(subSysId) ? "主菜单" : subSysId; } private string GetMenuNodeText(DataRow row) { string caption = GetRowValue(row, "MenuCaption"); if (string.IsNullOrWhiteSpace(caption)) { caption = GetRowValue(row, "SearchMenuCaption"); } if (string.IsNullOrWhiteSpace(caption)) { caption = row["MenuStruct"] + ""; } return caption; } private string GetRowValue(DataRow row, string columnName) { if (row == null || row.Table == null || !row.Table.Columns.Contains(columnName)) return string.Empty; return row[columnName] + ""; } private DataTable GetCodeSchemes() { string sql = "SELECT * FROM P_CodeSchemeTab ORDER BY MenuKey, SchemeId"; return SqlHelper.ExecuteDataTable(sql); } private DataTable GetSchemeControls(int schemeId) { string sql = string.Format("SELECT * FROM {0} WHERE {1} = @SchemeId{2}", CodeSchemeStorage.QuoteSqlIdentifier(SchemeControlTableName), CodeSchemeStorage.QuoteSqlIdentifier(NumberRuleSchemeIdColumn), GetNumberRuleOrderByClause(SchemeControlTableName)); return SqlHelper.ExecuteDataTable(sql, new SqlParameter[] { new SqlParameter("@SchemeId", schemeId) }); } private TreeNodeData CreatePendingCodeScheme(TreeNodeData menuData, string schemeName) { if (menuData == null || menuData.MenuRow == null) return null; string schemeCode = "CD" + Guid.NewGuid().ToString("N"); return new TreeNodeData { NodeType = NodeTypeScheme, MenuKey = menuData.MenuKey, MenuRow = menuData.MenuRow, MenuCaption = menuData.MenuCaption, ModuleCode = menuData.ModuleCode, SchemeId = 0, SchemeCode = schemeCode, SchemeName = schemeName, BindModule = false }; } private int InsertCodeScheme(TreeNodeData nodeData, string schemeName) { if (nodeData == null || nodeData.MenuRow == null) return 0; string schemeCode = string.IsNullOrWhiteSpace(nodeData.SchemeCode) ? "CD" + Guid.NewGuid().ToString("N") : nodeData.SchemeCode; ApplyBindModuleToNodeData(nodeData); string moduleCode = GetMenuModuleCode(nodeData); string sql = @"INSERT INTO P_CodeSchemeTab (SchemeCode, SchemeName, MenuKey, SubSysId, MenuId, MenuStruct, MenuCaption, ModuleCode, BindModule, BindSubSysId, BindMenuStruct1, BindMenuStruct2, BindMenuId, BindModuleCode, IsDefault, CreateUserId, CreateUserName, CreateTime) VALUES (@SchemeCode, @SchemeName, @MenuKey, @SubSysId, @MenuId, @MenuStruct, @MenuCaption, @ModuleCode, @BindModule, @BindSubSysId, @BindMenuStruct1, @BindMenuStruct2, @BindMenuId, @BindModuleCode, 0, @CreateUserId, @CreateUserName, GETDATE()); SELECT CAST(SCOPE_IDENTITY() AS INT);"; object result = SqlHelper.ExecuteScalar(CommandType.Text, sql, new SqlParameter[] { new SqlParameter("@SchemeCode", schemeCode), new SqlParameter("@SchemeName", schemeName), new SqlParameter("@MenuKey", nodeData.MenuKey), new SqlParameter("@SubSysId", GetRowValue(nodeData.MenuRow, "SubSysId")), new SqlParameter("@MenuId", GetRowValue(nodeData.MenuRow, "MenuId")), new SqlParameter("@MenuStruct", GetRowValue(nodeData.MenuRow, "MenuStruct")), new SqlParameter("@MenuCaption", GetTreeNodeCaption(nodeData)), new SqlParameter("@ModuleCode", moduleCode), new SqlParameter("@BindModule", nodeData.BindModule), new SqlParameter("@BindSubSysId", GetDbValue(nodeData.BindSubSysId)), new SqlParameter("@BindMenuStruct1", GetDbValue(nodeData.BindMenuStruct1)), new SqlParameter("@BindMenuStruct2", GetDbValue(nodeData.BindMenuStruct2)), new SqlParameter("@BindMenuId", GetDbValue(nodeData.BindMenuId)), new SqlParameter("@BindModuleCode", GetDbValue(nodeData.BindModuleCode)), new SqlParameter("@CreateUserId", ERPInfo.Instance.UserId), new SqlParameter("@CreateUserName", ERPInfo.Instance.UserName) }); nodeData.SchemeCode = schemeCode; return ToInt(result); } private void DeleteCodeScheme(TreeNodeData nodeData) { int schemeId = nodeData == null ? 0 : nodeData.SchemeId; if (schemeId <= 0) return; string bindModuleCode = nodeData.BindModule ? nodeData.BindModuleCode : string.Empty; DeleteCodeSchemeData(schemeId, bindModuleCode); } private void DeleteCodeSchemeData(int schemeId, string bindModuleCode) { if (schemeId <= 0) return; DeleteRuleRows(SchemeControlTableName, schemeId); if (!string.IsNullOrWhiteSpace(bindModuleCode)) { DeleteBindModuleNumberRuleRows(bindModuleCode); } string sql = "DELETE FROM P_CodeSchemeTab WHERE SchemeId = @SchemeId"; SqlHelper.ExecuteNonQuery(CommandType.Text, sql, new SqlParameter[] { new SqlParameter("@SchemeId", schemeId) }); } private void DeleteDisabledCodeSchemes() { if (!CodeSchemeStorage.TableExists(SchemeTableName) || !CodeSchemeStorage.ColumnExists(SchemeTableName, DesignRuleUseColumn)) return; string sql = "SELECT SchemeId, BindModule, BindModuleCode FROM P_CodeSchemeTab WHERE ISNULL(UseEd, 1) = 0"; DataTable table = SqlHelper.ExecuteDataTable(sql); if (table == null || table.Rows.Count == 0) return; foreach (DataRow row in table.Rows) { int schemeId = ToInt(row["SchemeId"]); string bindModuleCode = ToBool(row["BindModule"]) ? row["BindModuleCode"] + "" : string.Empty; DeleteRuleRows(SchemeControlTableName, schemeId); if (!string.IsNullOrWhiteSpace(bindModuleCode) && !BindModuleOwnedByEnabledScheme(bindModuleCode)) { DeleteBindModuleNumberRuleRows(bindModuleCode); } string deleteSql = "DELETE FROM P_CodeSchemeTab WHERE SchemeId = @SchemeId"; SqlHelper.ExecuteNonQuery(CommandType.Text, deleteSql, new SqlParameter[] { new SqlParameter("@SchemeId", schemeId) }); } } private bool BindModuleOwnedByEnabledScheme(string bindModuleCode) { if (string.IsNullOrWhiteSpace(bindModuleCode) || !CodeSchemeStorage.TableExists(SchemeTableName) || !CodeSchemeStorage.ColumnExists(SchemeTableName, DesignRuleUseColumn)) return false; string sql = @" SELECT COUNT(1) FROM P_CodeSchemeTab WHERE ISNULL(UseEd, 1) = 1 AND ISNULL(BindModule, 0) = 1 AND ISNULL(BindModuleCode, '') = @BindModuleCode"; object result = SqlHelper.ExecuteScalar(CommandType.Text, sql, new SqlParameter[] { new SqlParameter("@BindModuleCode", bindModuleCode) }); return ToInt(result) > 0; } private string GetNextSchemeName(string menuKey) { int serial = 1; while (true) { string schemeName = "方案" + serial; string sql = "SELECT COUNT(1) FROM P_CodeSchemeTab WHERE MenuKey = @MenuKey AND SchemeName = @SchemeName"; object result = SqlHelper.ExecuteScalar(CommandType.Text, sql, new SqlParameter[] { new SqlParameter("@MenuKey", menuKey), new SqlParameter("@SchemeName", schemeName) }); if (Convert.ToInt32(result) == 0 && !SchemeNameExistsInTree(menuKey, schemeName)) return schemeName; serial++; } } private bool SchemeNameExistsInTree(string menuKey, string schemeName) { foreach (TreeListNode node in this.treeMenu.Nodes) { if (SchemeNameExistsInTreeNode(node, menuKey, schemeName)) { return true; } } return false; } private bool SchemeNameExistsInTreeNode(TreeListNode node, string menuKey, string schemeName) { if (node == null) return false; TreeNodeData nodeData = node.Tag as TreeNodeData; if (nodeData != null && NodeTypeScheme.Equals(nodeData.NodeType) && string.Equals(nodeData.MenuKey, menuKey, StringComparison.OrdinalIgnoreCase) && string.Equals(nodeData.SchemeName, schemeName, StringComparison.OrdinalIgnoreCase)) { return true; } foreach (TreeListNode child in node.Nodes) { if (SchemeNameExistsInTreeNode(child, menuKey, schemeName)) { return true; } } return false; } private string GetMenuModuleCode(TreeNodeData menuData) { if (menuData != null && !string.IsNullOrWhiteSpace(menuData.ModuleCode)) { return menuData.ModuleCode; } if (menuData != null && menuData.MenuRow != null) { string moduleCode = GetRowValue(menuData.MenuRow, "ModuleCode"); if (!string.IsNullOrWhiteSpace(moduleCode)) return moduleCode; string purviewId = GetRowValue(menuData.MenuRow, "PurviewId"); if (!string.IsNullOrWhiteSpace(purviewId)) return purviewId; moduleCode = GetRowValue(menuData.MenuRow, "ModeCode"); if (!string.IsNullOrWhiteSpace(moduleCode)) return moduleCode; } return this.Model == null ? string.Empty : this.Model.ModuleCode; } private string GetTreeNodeCaption(TreeNodeData nodeData) { if (nodeData == null) return string.Empty; if (!string.IsNullOrWhiteSpace(nodeData.MenuCaption)) return nodeData.MenuCaption; return GetMenuNodeText(nodeData.MenuRow); } private static int ToInt(object value) { if (value == null || value == DBNull.Value) return 0; int result; return int.TryParse(value + "", out result) ? result : 0; } private static bool ToBool(object value) { if (value == null || value == DBNull.Value) return false; string text = (value + "").Trim(); return string.Equals(text, "1", StringComparison.OrdinalIgnoreCase) || string.Equals(text, "True", StringComparison.OrdinalIgnoreCase) || string.Equals(text, "是", StringComparison.OrdinalIgnoreCase); } private static object GetDbValue(string value) { return string.IsNullOrWhiteSpace(value) ? (object)DBNull.Value : value; } private void OnTreeMenuMouseDown(object sender, MouseEventArgs e) { TreeListHitInfo hitInfo = this.treeMenu.CalcHitInfo(e.Location); if (hitInfo == null || hitInfo.Node == null) return; if (e.Button != MouseButtons.Right) return; this.treeMenu.FocusedNode = hitInfo.Node; if (this.treeMenu.FocusedNode != hitInfo.Node) return; if (!IsDesignMode()) return; this.menuAddScheme.Enabled = CanAddScheme(hitInfo.Node); if (this.menuAddScheme.Enabled) { this.cmsMenuTree.Show(this.treeMenu, e.Location); } } private void OnTreeMenuBeforeFocusNode(object sender, BeforeFocusNodeEventArgs e) { if (this._restoringFocusedNode) return; if (e == null || e.Node == null) return; if (this._currentSchemeNode == null || e.Node == this._currentSchemeNode) return; CommitDesignRuleGridEditor(); if (!this._currentSchemeDirty && !HasPendingSchemeChanges()) return; if (!ConfirmAbandonCurrentSchemeChanges()) { e.CanFocus = false; return; } DiscardCurrentSchemeChanges(); } private void OnTreeMenuFocusedNodeChanged(object sender, FocusedNodeChangedEventArgs e) { if (this._restoringFocusedNode) return; if (e.Node == null) return; TreeNodeData nodeData = e.Node.Tag as TreeNodeData; if (nodeData == null) return; if (this._currentSchemeNode != null && e.Node != this._currentSchemeNode && this._currentSchemeDirty) { if (this._suppressNextFocusPrompt) { this._suppressNextFocusPrompt = false; RestoreFocusedSchemeNode(); return; } if (!ConfirmAbandonCurrentSchemeChanges()) { SuppressNextFocusPromptOnce(); RestoreFocusedSchemeNode(); return; } DiscardCurrentSchemeChanges(); } if (NodeTypeScheme.Equals(nodeData.NodeType)) { LoadScheme(e.Node); } else if (CanAddScheme(e.Node)) { ClearCurrentSchemeContext(); this.lblDesignerStatus.Text = IsDesignMode() ? "右键当前末级菜单可添加方案" : "请选择方案"; } } private bool IsMenuNode(TreeListNode node) { TreeNodeData nodeData = node == null ? null : node.Tag as TreeNodeData; return nodeData != null && NodeTypeMenu.Equals(nodeData.NodeType); } private bool HasMenuChildren(TreeListNode node) { if (node == null) return false; foreach (TreeListNode child in node.Nodes) { if (IsMenuNode(child)) return true; } return false; } private bool CanAddScheme(TreeListNode node) { TreeNodeData nodeData = node == null ? null : node.Tag as TreeNodeData; return nodeData != null && NodeTypeMenu.Equals(nodeData.NodeType) && !HasMenuChildren(node); } private void OnAddSchemeClick(object sender, EventArgs e) { if (!IsDesignMode()) return; TreeListNode menuNode = this.treeMenu.FocusedNode; if (!CanAddScheme(menuNode)) { MessageUtil.Show("只能在末级菜单节点下添加方案。"); return; } TreeNodeData menuData = menuNode.Tag as TreeNodeData; if (menuData == null) return; try { string schemeName = GetNextSchemeName(menuData.MenuKey); TreeNodeData schemeData = CreatePendingCodeScheme(menuData, schemeName); if (schemeData == null) { MessageUtil.Show("方案新增失败。"); return; } int schemeIconIndex = Math.Min(3, this.imgMenuTree.Images.Count - 1); TreeListNode schemeNode = AppendTreeNode(menuNode, schemeName, schemeData, schemeIconIndex); menuNode.Expanded = true; this.treeMenu.FocusedNode = schemeNode; } catch (Exception ex) { LogHelper.Instance.WriteError(ex); MessageUtil.Show("方案新增失败:" + ex.Message); } } private void OnSchemeNameKeyDown(object sender, KeyEventArgs e) { if (!IsDesignMode()) return; if (e.KeyCode != Keys.Enter) return; e.SuppressKeyPress = true; OnSaveSchemeClick(sender, EventArgs.Empty); } private void OnSchemeNameChanged(object sender, EventArgs e) { if (!IsDesignMode()) return; if (this._loadingSchemeEditor || this._currentSchemeNode == null) return; TreeNodeData nodeData = this._currentSchemeNode.Tag as TreeNodeData; if (nodeData != null && NodeTypeScheme.Equals(nodeData.NodeType)) { this._currentSchemeDirty = true; } } private void OnSaveSchemeClick(object sender, EventArgs e) { if (!IsDesignMode()) return; if (SaveSchemeAndRules()) { MessageUtil.Show("方案保存成功。"); } } private void EnsureIndexIfColumnsExist(string tableName, string[] columnNames, string indexName, string createSql) { if (string.IsNullOrWhiteSpace(tableName) || columnNames == null) return; foreach (string columnName in columnNames) { if (!CodeSchemeStorage.ColumnExists(tableName, columnName)) return; } CodeSchemeStorage.EnsureIndexIfColumnsExist(tableName, columnNames, indexName, createSql); } private void LoadBindMenuSource() { this._allMenus = MainImpl.GetMenusByMenuType(out this._menuSql); if (LanguageTranslation.Translatable) { this._allMenus = LanguageTranslation.InitialTableTranslation(this._allMenus); } } private DataTable LoadSpeciesTreeTable() { string sql = @"SELECT SpeciesNo, SpeciesName FROM PLM_AutoNumberSpeciesTab WHERE ISNULL(SpeciesNo, '') <> '' ORDER BY SpeciesNo"; DataTable treeTable = BaseImpl.GetDataTableResult(sql); return treeTable ?? new DataTable(); } private void BindSpeciesTree(DataTable treeTable) { if (treeTable == null || treeTable.Rows.Count == 0) return; if (!treeTable.Columns.Contains("SpeciesNo")) { throw new InvalidOperationException("编码分类数据源缺少列[SpeciesNo]。"); } if (!treeTable.Columns.Contains("SpeciesName")) { throw new InvalidOperationException("编码分类数据源缺少列[SpeciesName]。"); } List rows = treeTable.Rows.Cast() .Where(n => !string.IsNullOrWhiteSpace(GetRowValue(n, "SpeciesNo"))) .OrderBy(n => GetRowValue(n, "SpeciesNo")) .ToList(); if (rows.Count == 0) return; int treeDigit = GetRowValue(rows[0], "SpeciesNo").Length; Dictionary nodeMap = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (DataRow row in rows) { string speciesNo = GetRowValue(row, "SpeciesNo").Trim(); if (string.IsNullOrWhiteSpace(speciesNo) || nodeMap.ContainsKey(speciesNo)) continue; string speciesName = GetRowValue(row, "SpeciesName").Trim(); string nodeText = string.IsNullOrWhiteSpace(speciesName) ? speciesNo : speciesName; TreeListNode parentNode = GetSpeciesParentNode(row, speciesNo, treeDigit, nodeMap); TreeListNode node = AppendTreeNode(parentNode, nodeText, new TreeNodeData { NodeType = NodeTypeMenu, MenuKey = speciesNo, MenuLevel = GetSpeciesNodeLevel(speciesNo, treeDigit), MenuRow = row, MenuCaption = nodeText, ModuleCode = GetNumberRuleGridModuleCode() }, GetNextTreeIconIndex()); nodeMap.Add(speciesNo, node); } AppendCodeSchemeNodes(nodeMap); } private TreeListNode GetSpeciesParentNode(DataRow row, string speciesNo, int treeDigit, Dictionary nodeMap) { if (row != null && row.Table != null && SystemInfo.Instance.TreeSpecialBinding && row.Table.Columns.Contains("pid")) { string pid = GetRowValue(row, "pid").Trim(); return !string.IsNullOrWhiteSpace(pid) && nodeMap.ContainsKey(pid) ? nodeMap[pid] : null; } if (treeDigit <= 0 || string.IsNullOrWhiteSpace(speciesNo) || speciesNo.Length < treeDigit * 2) return null; string parentKey = speciesNo.Substring(0, speciesNo.Length - treeDigit); return nodeMap.ContainsKey(parentKey) ? nodeMap[parentKey] : null; } private int GetSpeciesNodeLevel(string speciesNo, int treeDigit) { if (treeDigit <= 0 || string.IsNullOrWhiteSpace(speciesNo)) return 1; return Math.Max(1, (int)Math.Ceiling(speciesNo.Length * 1.0 / treeDigit)); } private DataTable LoadConfiguredMenuTreeTable() { this._menuTreeSourceRow = null; this._menuTreeKeyField = string.Empty; this._menuTreeTextField = string.Empty; this._menuTreeNodeLength = string.Empty; string moduleCode = this.Model == null ? string.Empty : this.Model.ModuleCode; if (string.IsNullOrWhiteSpace(moduleCode)) { throw new InvalidOperationException("未获取到 ModuleCode,无法加载左侧配置树。"); } this._menuTreeSourceRow = BaseModuleImpl.GetBaseLeftTreeField(moduleCode); if (this._menuTreeSourceRow == null) { throw new InvalidOperationException(string.Format("模块[{0}]未配置左侧树节点关联。", moduleCode)); } string fieldSql = GetRowValue(this._menuTreeSourceRow, "fieldsql"); this._menuTreeKeyField = GetRowValue(this._menuTreeSourceRow, "fieldsqlid"); this._menuTreeTextField = GetRowValue(this._menuTreeSourceRow, "fieldsqlname"); this._menuTreeNodeLength = GetRowValue(this._menuTreeSourceRow, "TreeNodeLength"); if (string.IsNullOrWhiteSpace(fieldSql)) { throw new InvalidOperationException("左侧树节点关联未配置 fieldsql。"); } if (string.IsNullOrWhiteSpace(this._menuTreeKeyField)) { throw new InvalidOperationException("左侧树节点关联未配置 fieldsqlid。"); } if (string.IsNullOrWhiteSpace(this._menuTreeTextField)) { throw new InvalidOperationException("左侧树节点关联未配置 fieldsqlname。"); } DataTable treeTable = BaseImpl.GetDataTableResult(fieldSql); if (treeTable == null) { treeTable = new DataTable(); } if (!treeTable.Columns.Contains(this._menuTreeKeyField)) { throw new InvalidOperationException(string.Format("左侧树数据源缺少节点编号列[{0}]。", this._menuTreeKeyField)); } if (!treeTable.Columns.Contains(this._menuTreeTextField)) { throw new InvalidOperationException(string.Format("左侧树数据源缺少节点名称列[{0}]。", this._menuTreeTextField)); } return treeTable; } private void BindConfiguredMenuTree(DataTable treeTable) { if (treeTable == null || treeTable.Rows.Count == 0) return; List rows = GetConfiguredTreeRows(treeTable); Dictionary nodeMap = new Dictionary(StringComparer.OrdinalIgnoreCase); List pendingRows = rows.ToList(); while (pendingRows.Count > 0) { bool appended = false; for (int i = pendingRows.Count - 1; i >= 0; i--) { DataRow row = pendingRows[i]; string nodeKey = GetConfiguredTreeNodeKey(row); if (string.IsNullOrWhiteSpace(nodeKey) || nodeMap.ContainsKey(nodeKey)) { pendingRows.RemoveAt(i); continue; } string parentKey = GetConfiguredTreeParentKey(row, rows); bool hasParent = !string.IsNullOrWhiteSpace(parentKey) && nodeMap.ContainsKey(parentKey); if (!hasParent && ConfiguredTreeKeyExists(rows, parentKey)) { continue; } TreeListNode parentNode = hasParent ? nodeMap[parentKey] : null; string nodeText = GetConfiguredTreeNodeText(row); TreeListNode node = AppendTreeNode(parentNode, nodeText, new TreeNodeData { NodeType = NodeTypeMenu, MenuKey = nodeKey, MenuLevel = GetConfiguredTreeNodeLevel(row), MenuRow = row, MenuCaption = nodeText, ModuleCode = GetConfiguredTreeNodeModuleCode(row) }, GetNextTreeIconIndex()); nodeMap.Add(nodeKey, node); pendingRows.RemoveAt(i); appended = true; } if (!appended) { break; } } AppendCodeSchemeNodes(nodeMap); } private bool ConfiguredTreeKeyExists(List rows, string nodeKey) { if (rows == null || string.IsNullOrWhiteSpace(nodeKey)) return false; return rows.Any(n => string.Equals(GetConfiguredTreeNodeKey(n), nodeKey, StringComparison.OrdinalIgnoreCase)); } private List GetConfiguredTreeRows(DataTable treeTable) { IEnumerable rows = treeTable.Rows.Cast() .Where(n => !string.IsNullOrWhiteSpace(GetConfiguredTreeNodeKey(n))); int lengthLimitation; if (int.TryParse(this._menuTreeNodeLength, out lengthLimitation) && lengthLimitation > 0) { rows = rows.OrderBy(n => GetConfiguredTreeNodeKey(n).Length > lengthLimitation ? 1 : 0) .ThenBy(n => GetConfiguredTreeSortValue(n)) .ThenBy(n => GetConfiguredTreeNodeKey(n)); } else { rows = rows.OrderBy(n => GetConfiguredTreeNodeKey(n)); } return rows.ToList(); } private string GetConfiguredTreeNodeKey(DataRow row) { return GetRowValue(row, this._menuTreeKeyField).Trim(); } private string GetConfiguredTreeNodeText(DataRow row) { string text = GetRowValue(row, this._menuTreeTextField).Trim(); if (!string.IsNullOrWhiteSpace(text)) return text; return GetConfiguredTreeNodeKey(row); } private string GetConfiguredTreeSortValue(DataRow row) { if (row != null && row.Table != null && row.Table.Columns.Contains("remark")) { return GetRowValue(row, "remark"); } return GetConfiguredTreeNodeKey(row); } private string GetConfiguredTreeParentKey(DataRow row, List allRows) { string nodeKey = GetConfiguredTreeNodeKey(row); if (string.IsNullOrWhiteSpace(nodeKey)) return string.Empty; string pidColumn = FindColumnName(row == null ? null : row.Table, "pid", "Pid", "ParentId", "ParentKey", "ParentNo"); if (!string.IsNullOrWhiteSpace(pidColumn)) { string pid = GetRowValue(row, pidColumn).Trim(); if (!string.IsNullOrWhiteSpace(pid) && pid != "0") return pid; } int lengthLimitation; if (int.TryParse(this._menuTreeNodeLength, out lengthLimitation) && lengthLimitation > 0 && nodeKey.Length > lengthLimitation) { string prefixKey = nodeKey.Substring(0, lengthLimitation); string sortValue = GetConfiguredTreeSortValue(row); if (!string.IsNullOrWhiteSpace(sortValue) && sortValue.Contains("-")) { string parentSortValue = sortValue.Remove(sortValue.LastIndexOf("-"), sortValue.Length - sortValue.LastIndexOf("-")); DataRow parentRow = allRows.FirstOrDefault(n => GetConfiguredTreeNodeKey(n).StartsWith(prefixKey, StringComparison.OrdinalIgnoreCase) && string.Equals(GetConfiguredTreeSortValue(n), parentSortValue, StringComparison.OrdinalIgnoreCase)); if (parentRow != null) return GetConfiguredTreeNodeKey(parentRow); } return prefixKey; } int treeDigit = GetConfiguredTreeDigit(allRows); if (treeDigit > 0 && nodeKey.Length >= treeDigit * 2) { return nodeKey.Substring(0, nodeKey.Length - treeDigit); } return string.Empty; } private int GetConfiguredTreeDigit(List rows) { if (rows == null) return 0; DataRow firstRow = rows.FirstOrDefault(n => !string.IsNullOrWhiteSpace(GetConfiguredTreeNodeKey(n))); return firstRow == null ? 0 : GetConfiguredTreeNodeKey(firstRow).Length; } private int GetConfiguredTreeNodeLevel(DataRow row) { string nodeKey = GetConfiguredTreeNodeKey(row); int treeDigit = GetConfiguredTreeDigit(row == null ? null : row.Table.Rows.Cast().ToList()); if (treeDigit <= 0 || string.IsNullOrWhiteSpace(nodeKey)) return 1; return Math.Max(1, (int)Math.Ceiling(nodeKey.Length * 1.0 / treeDigit)); } private string GetConfiguredTreeNodeModuleCode(DataRow row) { string moduleCode = GetRowValue(row, "ModuleCode"); if (!string.IsNullOrWhiteSpace(moduleCode)) return moduleCode; moduleCode = GetRowValue(row, "PurviewId"); if (!string.IsNullOrWhiteSpace(moduleCode)) return moduleCode; moduleCode = GetRowValue(row, "ModeCode"); if (!string.IsNullOrWhiteSpace(moduleCode)) return moduleCode; return this.Model == null ? string.Empty : this.Model.ModuleCode; } private void OnAddLogicClick(object sender, EventArgs e) { if (!IsDesignMode()) return; if (!EnsureNumberRuleGridReady()) return; TreeNodeData nodeData = this._currentSchemeNode == null ? null : this._currentSchemeNode.Tag as TreeNodeData; if (nodeData == null || !NodeTypeScheme.Equals(nodeData.NodeType)) { MessageUtil.Show("请先选择方案。"); return; } try { this.gridDesignRules.AddNewLogic(); this._currentSchemeDirty = true; UpdateSchemeStatus(); } catch (Exception ex) { LogHelper.Instance.WriteError(ex); MessageUtil.Show("增加逻辑失败:" + ex.Message); } } private void OnDeleteLogicClick(object sender, EventArgs e) { if (!IsDesignMode()) return; if (!EnsureNumberRuleGridReady()) return; try { TreeNodeData nodeData = this._currentSchemeNode == null ? null : this._currentSchemeNode.Tag as TreeNodeData; if (nodeData == null || !NodeTypeScheme.Equals(nodeData.NodeType)) { MessageUtil.Show("请先选择方案。"); return; } if (DeleteSelectedNumberRuleRows()) { this._currentSchemeDirty = true; UpdateSchemeStatus(); } } catch (Exception ex) { LogHelper.Instance.WriteError(ex); MessageUtil.Show("删除逻辑失败:" + ex.Message); } } private void OnDeleteSchemeClick(object sender, EventArgs e) { if (!IsDesignMode()) return; TreeListNode schemeNode = this._currentSchemeNode; TreeNodeData nodeData = schemeNode == null ? null : schemeNode.Tag as TreeNodeData; if (nodeData == null || !NodeTypeScheme.Equals(nodeData.NodeType)) return; DialogResult result = MessageUtil.Show("确定要删除当前方案吗?", MessageBoxButtons.OKCancel); if (result != DialogResult.OK) return; try { if (nodeData.SchemeId > 0) { DeleteCodeScheme(nodeData); } RemoveSchemeNodeAndClear(schemeNode); MessageUtil.Show("方案删除成功。"); } catch (Exception ex) { LogHelper.Instance.WriteError(ex); MessageUtil.Show("方案删除失败:" + ex.Message); } } private void OnGenerateCodeClick(object sender, EventArgs e) { if (!IsViewMode()) return; TreeNodeData nodeData = this._currentSchemeNode == null ? null : this._currentSchemeNode.Tag as TreeNodeData; if (nodeData == null || !NodeTypeScheme.Equals(nodeData.NodeType)) { MessageUtil.Show("请先选择方案。"); return; } if (nodeData.BindModule) { MessageUtil.Show("当前方案已绑定模块,view模式只支持未绑定方案生成编码。"); return; } try { string codeValue = GenerateCodeByScheme(nodeData); if (string.IsNullOrWhiteSpace(codeValue)) return; this.txtCodePreview.Text = codeValue; MessageUtil.Show("编码生成成功。"); } catch (Exception ex) { LogHelper.Instance.WriteError(ex); MessageUtil.Show("编码生成失败:" + ex.Message); } } private string GenerateCodeByScheme(TreeNodeData nodeData) { if (nodeData == null || nodeData.SchemeId <= 0) return string.Empty; CodeSchemeStorage.EnsureCodeRecordStorage(); CodeSchemeStorage.EnsureCodeGenerateProcedure(); return ExecuteCodeGenerateProcedure(nodeData); } private string ExecuteCodeGenerateProcedure(TreeNodeData nodeData) { string sql = string.Format(@" DECLARE @return_id NVARCHAR(300); EXEC dbo.{0} @SchemeId = @SchemeId, @CreateUserId = @CreateUserId, @CreateUserName = @CreateUserName, @return_id = @return_id OUTPUT; SELECT @return_id;", CodeGenerateProcedureName); object result = SqlHelper.ExecuteScalar(CommandType.Text, sql, new SqlParameter[] { new SqlParameter("@SchemeId", nodeData.SchemeId), new SqlParameter("@CreateUserId", ERPInfo.Instance.UserId ?? string.Empty), new SqlParameter("@CreateUserName", ERPInfo.Instance.UserName ?? string.Empty) }); return result + ""; } private bool SaveSchemeAndRules() { TreeNodeData nodeData = this._currentSchemeNode == null ? null : this._currentSchemeNode.Tag as TreeNodeData; if (nodeData == null || !NodeTypeScheme.Equals(nodeData.NodeType)) return false; if (!CanSaveBindModuleRules(nodeData)) return false; if (!SaveCurrentScheme(false)) return false; nodeData = this._currentSchemeNode == null ? null : this._currentSchemeNode.Tag as TreeNodeData; if (!SaveNumberRuleGrid(nodeData)) { this._currentSchemeDirty = true; UpdateSchemeStatus(); return false; } this._currentSchemeDirty = false; UpdateSchemeStatus(); return true; } private bool CanSaveBindModuleRules(TreeNodeData nodeData) { if (nodeData == null || !IsDesignMode() || !this.chkBindModule.Checked) return true; string bindModuleCode = GetSelectedBindModuleCode(); if (string.IsNullOrWhiteSpace(bindModuleCode)) return true; bool isNewBindScheme = nodeData.SchemeId <= 0; bool isChangingToBind = !nodeData.BindModule; bool isChangingBindModule = nodeData.BindModule && !string.Equals(nodeData.BindModuleCode, bindModuleCode, StringComparison.OrdinalIgnoreCase); if (!isNewBindScheme && !isChangingToBind && !isChangingBindModule) return true; string ownerSchemeName; if (BindModuleOwnedByOtherScheme(bindModuleCode, nodeData.SchemeId, out ownerSchemeName)) { MessageUtil.Show(string.Format("当前选择的绑定模块已经被方案[{0}]绑定,不能重复绑定。", ownerSchemeName)); return false; } if (!BindModuleNumberRulesExist(bindModuleCode)) return true; DialogResult result = MessageUtil.Show( "当前选择的绑定模块存在未归属方案的历史编码规则。\r\n确认后将由当前方案接管,并覆盖原有历史规则,是否继续?", MessageBoxButtons.YesNo); if (result != DialogResult.Yes) return false; return true; } private bool SaveCurrentScheme(bool showSuccess = true) { if (!IsDesignMode()) return false; if (this._currentSchemeNode == null) return false; TreeNodeData nodeData = this._currentSchemeNode.Tag as TreeNodeData; if (nodeData == null || !NodeTypeScheme.Equals(nodeData.NodeType)) return false; string schemeName = (this.txtSchemeName.Text + "").Trim(); if (string.IsNullOrWhiteSpace(schemeName)) { MessageUtil.Show("方案名称不能为空。"); this.txtSchemeName.Focus(); return false; } if (this.chkBindModule.Checked && string.IsNullOrWhiteSpace(GetSelectedBindModuleCode())) { MessageUtil.Show("请选择绑定模块的三级菜单。"); this.cboBindLevel3.Focus(); return false; } try { ApplyBindModuleToNodeData(nodeData); if (nodeData.SchemeId <= 0) { int schemeId = InsertCodeScheme(nodeData, schemeName); if (schemeId <= 0) { MessageUtil.Show("方案保存失败。"); return false; } nodeData.SchemeId = schemeId; } else { string sql = @"UPDATE P_CodeSchemeTab SET SchemeName = @SchemeName, ModuleCode = @ModuleCode, BindModule = @BindModule, BindSubSysId = @BindSubSysId, BindMenuStruct1 = @BindMenuStruct1, BindMenuStruct2 = @BindMenuStruct2, BindMenuId = @BindMenuId, BindModuleCode = @BindModuleCode, ModifyUserId = @ModifyUserId, ModifyUserName = @ModifyUserName, ModifyTime = GETDATE() WHERE SchemeId = @SchemeId"; SqlHelper.ExecuteNonQuery(CommandType.Text, sql, new SqlParameter[] { new SqlParameter("@SchemeName", schemeName), new SqlParameter("@ModuleCode", GetMenuModuleCode(nodeData)), new SqlParameter("@BindModule", nodeData.BindModule), new SqlParameter("@BindSubSysId", GetDbValue(nodeData.BindSubSysId)), new SqlParameter("@BindMenuStruct1", GetDbValue(nodeData.BindMenuStruct1)), new SqlParameter("@BindMenuStruct2", GetDbValue(nodeData.BindMenuStruct2)), new SqlParameter("@BindMenuId", GetDbValue(nodeData.BindMenuId)), new SqlParameter("@BindModuleCode", GetDbValue(nodeData.BindModuleCode)), new SqlParameter("@ModifyUserId", ERPInfo.Instance.UserId), new SqlParameter("@ModifyUserName", ERPInfo.Instance.UserName), new SqlParameter("@SchemeId", nodeData.SchemeId) }); } nodeData.SchemeName = schemeName; this._currentSchemeNode.SetValue(this.treeColumnMenu, schemeName); this._currentSchemeKey = GetSchemeKey(nodeData); this._currentSchemeDirty = false; UpdateSchemeStatus(); if (showSuccess) { MessageUtil.Show("方案保存成功。"); } return true; } catch (Exception ex) { LogHelper.Instance.WriteError(ex); MessageUtil.Show("方案保存失败:" + ex.Message); return false; } } private void SetSchemeEditor(TreeNodeData nodeData) { bool hasScheme = nodeData != null && NodeTypeScheme.Equals(nodeData.NodeType); bool designMode = IsDesignMode(); this._loadingSchemeEditor = true; try { this.txtSchemeName.Enabled = hasScheme; this.txtSchemeName.Properties.ReadOnly = !designMode; this.btnDeleteScheme.Enabled = designMode && hasScheme; this.btnGenerateCode.Enabled = !designMode && hasScheme; this.btnAddLogic.Enabled = designMode && hasScheme; this.btnDeleteLogic.Enabled = designMode && hasScheme; this.btnSave.Enabled = designMode && hasScheme; this.txtCodePreview.Enabled = hasScheme; this.txtSchemeName.Text = hasScheme ? nodeData.SchemeName : ""; SetBindModuleEditor(nodeData); if (!hasScheme) { this.txtCodePreview.Text = ""; } if (!hasScheme) { this.pnlViewWork.Controls.Clear(); } } finally { this._loadingSchemeEditor = false; } SetBindControlsEnabled(hasScheme); } private void SetBindModuleEditor(TreeNodeData nodeData) { this._loadingBindControls = true; try { bool hasScheme = nodeData != null && NodeTypeScheme.Equals(nodeData.NodeType); this.chkBindModule.Checked = hasScheme && nodeData.BindModule; string subSysId = hasScheme ? nodeData.BindSubSysId : string.Empty; string menuStruct1 = hasScheme ? nodeData.BindMenuStruct1 : string.Empty; string menuStruct2 = hasScheme ? nodeData.BindMenuStruct2 : string.Empty; string menuId = hasScheme ? nodeData.BindMenuId : string.Empty; if (hasScheme && nodeData.MenuRow != null) { if (string.IsNullOrWhiteSpace(subSysId)) { subSysId = GetRowValue(nodeData.MenuRow, "SubSysId"); } string currentStruct = GetRowValue(nodeData.MenuRow, "MenuStruct"); if (string.IsNullOrWhiteSpace(menuStruct1) && currentStruct.Length >= MenuStructStepLength) { menuStruct1 = currentStruct.Substring(0, MenuStructStepLength); } if (string.IsNullOrWhiteSpace(menuStruct2)) { menuStruct2 = currentStruct; } if (string.IsNullOrWhiteSpace(menuId)) { menuId = GetRowValue(nodeData.MenuRow, "MenuId"); } } LoadBindLevel1Items(subSysId); LoadBindLevel2Items(menuStruct1); LoadBindLevel3Items(menuStruct2, menuId); } finally { this._loadingBindControls = false; } } private void SetBindControlsEnabled(bool hasScheme) { bool enabled = IsDesignMode() && hasScheme; this.chkBindModule.Enabled = enabled; bool comboEnabled = enabled && this.chkBindModule.Checked; this.cboBindLevel1.Enabled = comboEnabled; this.cboBindLevel2.Enabled = comboEnabled && this.cboBindLevel1.SelectedItem is MenuComboItem; this.cboBindLevel3.Enabled = comboEnabled && this.cboBindLevel2.SelectedItem is MenuComboItem; } private void LoadBindLevel1Items(string selectedSubSysId) { object previousSelected = this.cboBindLevel1.SelectedItem; this.cboBindLevel1.Properties.Items.Clear(); List topSubSystems = GetVisibleTopSubSystems(this._allMenus); foreach (DataRow row in topSubSystems) { this.cboBindLevel1.Properties.Items.Add(new MenuComboItem { Text = GetTopNodeText(row), SubSysId = GetRowValue(row, "SubSysId"), Row = row }); } SelectComboItem(this.cboBindLevel1, selectedSubSysId, null, null); if (string.IsNullOrWhiteSpace(selectedSubSysId) && this.cboBindLevel1.SelectedItem == null && previousSelected is MenuComboItem) { MenuComboItem previousItem = previousSelected as MenuComboItem; SelectComboItem(this.cboBindLevel1, previousItem.SubSysId, null, null); } } private void LoadBindLevel2Items(string selectedMenuStruct) { MenuComboItem level1 = this.cboBindLevel1.SelectedItem as MenuComboItem; this.cboBindLevel2.Properties.Items.Clear(); this.cboBindLevel3.Properties.Items.Clear(); if (level1 != null && this._allMenus != null) { List rows = this._allMenus.Rows.Cast() .Where(IsMenuTreeRow) .Where(n => GetMenuLevel(GetRowValue(n, "MenuStruct")) == 1) .Where(n => string.Equals(GetRowValue(n, "SubSysId"), level1.SubSysId, StringComparison.OrdinalIgnoreCase)) .Where(n => !IsSplitBarMenu(n)) .OrderBy(n => GetRowValue(n, "MenuStruct")) .ThenBy(n => GetRowValue(n, "MenuId")) .ToList(); foreach (DataRow row in rows) { this.cboBindLevel2.Properties.Items.Add(new MenuComboItem { Text = GetMenuNodeText(row), SubSysId = GetRowValue(row, "SubSysId"), MenuStruct = GetRowValue(row, "MenuStruct"), MenuId = GetRowValue(row, "MenuId"), ModuleCode = GetRowValue(row, "PurviewId"), Row = row }); } } SelectComboItem(this.cboBindLevel2, null, selectedMenuStruct, null); } private void LoadBindLevel3Items(string selectedMenuStruct, string selectedMenuId) { MenuComboItem level2 = this.cboBindLevel2.SelectedItem as MenuComboItem; this.cboBindLevel3.Properties.Items.Clear(); if (level2 != null && this._allMenus != null) { List rows = this._allMenus.Rows.Cast() .Where(IsMenuTreeRow) .Where(n => GetMenuLevel(GetRowValue(n, "MenuStruct")) == MaxMenuStructLevel) .Where(n => string.Equals(GetRowValue(n, "SubSysId"), level2.SubSysId, StringComparison.OrdinalIgnoreCase)) .Where(n => GetRowValue(n, "MenuStruct").StartsWith(level2.MenuStruct)) .Where(n => !IsSplitBarMenu(n)) .Where(n => !string.IsNullOrWhiteSpace(GetRowValue(n, "DllFileName"))) .OrderBy(n => GetRowValue(n, "MenuStruct")) .ThenBy(n => GetRowValue(n, "MenuId")) .ToList(); foreach (DataRow row in rows) { this.cboBindLevel3.Properties.Items.Add(new MenuComboItem { Text = GetMenuNodeText(row), SubSysId = GetRowValue(row, "SubSysId"), MenuStruct = GetRowValue(row, "MenuStruct"), MenuId = GetRowValue(row, "MenuId"), ModuleCode = GetRowValue(row, "PurviewId"), Row = row }); } } SelectComboItem(this.cboBindLevel3, null, selectedMenuStruct, selectedMenuId); } private void SelectComboItem(DevExpress.XtraEditors.ComboBoxEdit combo, string subSysId, string menuStruct, string menuId) { if (combo == null) { return; } combo.SelectedIndex = -1; for (int i = 0; i < combo.Properties.Items.Count; i++) { MenuComboItem item = combo.Properties.Items[i] as MenuComboItem; if (item == null) continue; bool matched = true; if (!string.IsNullOrWhiteSpace(subSysId)) { matched = matched && string.Equals(item.SubSysId, subSysId, StringComparison.OrdinalIgnoreCase); } if (!string.IsNullOrWhiteSpace(menuStruct)) { matched = matched && string.Equals(item.MenuStruct, menuStruct, StringComparison.OrdinalIgnoreCase); } if (!string.IsNullOrWhiteSpace(menuId)) { matched = matched && string.Equals(item.MenuId, menuId, StringComparison.OrdinalIgnoreCase); } if (matched) { combo.SelectedIndex = i; return; } } } private void OnBindModuleCheckedChanged(object sender, EventArgs e) { if (this._loadingBindControls || this._loadingSchemeEditor) return; if (this.chkBindModule.Checked && this.cboBindLevel1.SelectedItem == null) { TreeNodeData nodeData = this._currentSchemeNode == null ? null : this._currentSchemeNode.Tag as TreeNodeData; SetBindModuleEditor(nodeData); this.chkBindModule.Checked = true; } SetBindControlsEnabled(this._currentSchemeNode != null); OnBindModuleEditorChanged(true); } private void OnBindLevel1Changed(object sender, EventArgs e) { if (this._loadingBindControls) return; this._loadingBindControls = true; try { LoadBindLevel2Items(null); LoadBindLevel3Items(null, null); } finally { this._loadingBindControls = false; } SetBindControlsEnabled(this._currentSchemeNode != null); OnBindModuleEditorChanged(true); } private void OnBindLevel2Changed(object sender, EventArgs e) { if (this._loadingBindControls) return; this._loadingBindControls = true; try { LoadBindLevel3Items(null, null); } finally { this._loadingBindControls = false; } SetBindControlsEnabled(this._currentSchemeNode != null); OnBindModuleEditorChanged(true); } private void OnBindLevel3Changed(object sender, EventArgs e) { if (this._loadingBindControls) return; SetBindControlsEnabled(this._currentSchemeNode != null); OnBindModuleEditorChanged(true); } private void OnBindModuleEditorChanged(bool reloadDesignRules) { if (this._loadingBindControls || this._loadingSchemeEditor) return; if (!IsDesignMode() || this._currentSchemeNode == null) return; this._currentSchemeDirty = true; UpdateSchemeStatus(); } private void ApplyBindModuleToNodeData(TreeNodeData nodeData) { if (nodeData == null) return; nodeData.BindModule = IsDesignMode() && this.chkBindModule.Checked; if (!nodeData.BindModule) { nodeData.BindSubSysId = string.Empty; nodeData.BindMenuStruct1 = string.Empty; nodeData.BindMenuStruct2 = string.Empty; nodeData.BindMenuId = string.Empty; nodeData.BindModuleCode = string.Empty; return; } MenuComboItem level1 = this.cboBindLevel1.SelectedItem as MenuComboItem; MenuComboItem level2 = this.cboBindLevel2.SelectedItem as MenuComboItem; MenuComboItem level3 = this.cboBindLevel3.SelectedItem as MenuComboItem; nodeData.BindSubSysId = level1 == null ? string.Empty : level1.SubSysId; nodeData.BindMenuStruct1 = level2 == null ? string.Empty : level2.MenuStruct; nodeData.BindMenuStruct2 = level3 == null ? string.Empty : level3.MenuStruct; nodeData.BindMenuId = level3 == null ? string.Empty : level3.MenuId; nodeData.BindModuleCode = GetSelectedBindModuleCode(); } private string GetSelectedBindModuleCode() { MenuComboItem level3 = this.cboBindLevel3.SelectedItem as MenuComboItem; if (level3 == null) return string.Empty; if (!string.IsNullOrWhiteSpace(level3.ModuleCode)) return level3.ModuleCode; return GetRowValue(level3.Row, "PurviewId"); } private string GetSchemeKey(TreeNodeData nodeData) { if (nodeData == null) return string.Empty; if (nodeData.SchemeId > 0) return nodeData.SchemeId + ""; if (!string.IsNullOrWhiteSpace(nodeData.SchemeCode)) return "new:" + nodeData.SchemeCode; return string.Empty; } private bool ConfirmAbandonCurrentSchemeChanges() { if (!IsDesignMode()) return true; if (!this._currentSchemeDirty && !HasPendingSchemeChanges()) return true; DialogResult result = MessageUtil.Show("当前方案存在未保存的修改。\r\n点击【确定】放弃修改并继续切换;\r\n点击【取消】返回后手动点击保存。", MessageBoxButtons.OKCancel); return result == DialogResult.OK; } private void SuppressNextFocusPromptOnce() { this._suppressNextFocusPrompt = true; BeginInvoke(new MethodInvoker(delegate { this._suppressNextFocusPrompt = false; })); } private void RestoreFocusedSchemeNode() { if (this._currentSchemeNode == null) return; try { this._restoringFocusedNode = true; this.treeMenu.FocusedNode = this._currentSchemeNode; } finally { this._restoringFocusedNode = false; } } private void DiscardCurrentSchemeChanges() { TreeListNode discardNode = this._currentSchemeNode; TreeNodeData nodeData = discardNode == null ? null : discardNode.Tag as TreeNodeData; this._currentSchemeDirty = false; if (nodeData == null || nodeData.SchemeId > 0) return; RemoveSchemeNodeAndClear(discardNode); } private void RemoveSchemeNodeAndClear(TreeListNode schemeNode) { try { this._restoringFocusedNode = true; if (schemeNode != null) { this.treeMenu.DeleteNode(schemeNode); } } finally { this._restoringFocusedNode = false; } if (schemeNode == this._currentSchemeNode) { this._currentSchemeNode = null; this._currentSchemeKey = string.Empty; this._currentSchemeDirty = false; this.pnlViewWork.Controls.Clear(); ClearViewRuntimeState(); BindEmptyDesignRuleGrid(); SetSchemeEditor(null); UpdateSchemeStatus(); } } private void ClearCurrentSchemeContext() { this._currentSchemeNode = null; this._currentSchemeKey = string.Empty; this._currentSchemeDirty = false; this.pnlViewWork.Controls.Clear(); ClearViewRuntimeState(); BindEmptyDesignRuleGrid(); SetSchemeEditor(null); } private void LoadScheme(TreeListNode schemeNode) { TreeNodeData nodeData = schemeNode.Tag as TreeNodeData; if (nodeData == null || !NodeTypeScheme.Equals(nodeData.NodeType)) return; string targetSchemeKey = GetSchemeKey(nodeData); this._currentSchemeNode = schemeNode; this._currentSchemeKey = targetSchemeKey; this.pnlViewWork.Controls.Clear(); ClearViewRuntimeState(); SetSchemeEditor(nodeData); try { if (nodeData.SchemeId > 0) { DataTable controls = LoadNumberRuleSchemeRows(nodeData); LoadSchemeDesignRules(controls); } else if (IsDesignMode()) { LoadSchemeDesignRules(null); } else { BindEmptyDesignRuleGrid(); } } catch (Exception ex) { LogHelper.Instance.WriteError(ex); MessageUtil.Show("方案控件加载失败:" + ex.Message); } this._currentSchemeDirty = IsDesignMode() && nodeData.SchemeId <= 0; UpdateSchemeStatus(); } private void LoadSchemeViewControls(DataTable schemeControls) { if (!IsViewMode()) return; EnsureModelDataCaches(); DataTable viewControls = CreateViewControlConfigTable(schemeControls); if (viewControls.Rows.Count == 0) { ClearCodePreview(); return; } this._viewControlObj = new MyControl(); this._viewControlObj.Model = this.Model; this._viewControlObj.CurrentData = this.Model == null ? null : this.Model.GetMaintabFocusedRow(); this._viewControlObj.OtherParams = this.Model == null ? null : this.Model.OtherParams(); this._viewControlObj.OnDataSourceBindCallBack += OnViewControlDataSourceBindCallBack; this._viewControlObj.InitControl(viewControls, this.pnlViewWork); this.pnlViewWork.Dock = DockStyle.Fill; ApplyCurrentRowValuesToViewControls(); RegisterViewControlValueChanged(this.pnlViewWork); ClearCodePreview(); } private void ClearViewRuntimeState() { this._viewControlObj = null; this._viewSchemeItems.Clear(); if (this.txtCodePreview != null) { this.txtCodePreview.Text = string.Empty; } } private void EnsureModelDataCaches() { if (this.Model == null) return; if (this.Model.DataCaches == null) { this.Model.DataCaches = new Dictionary(); } } private DataTable CreateViewControlConfigTable(DataTable schemeControls) { DataTable sourceTable = this._fieldConfigTable; DataTable result = sourceTable == null ? new DataTable() : sourceTable.Clone(); result.PrimaryKey = new DataColumn[0]; result.Constraints.Clear(); PrepareMyControlConfigTable(result); this._viewSchemeItems.Clear(); if (schemeControls == null || schemeControls.Rows.Count == 0 || sourceTable == null || sourceTable.Rows.Count == 0) { return result; } string fieldNameColumn = FindColumnName(result, "fieldname", "fieldName", "FieldName"); if (string.IsNullOrWhiteSpace(fieldNameColumn)) return result; string userNameColumn = FindColumnName(result, "username", "userName", "UserName"); string fieldTypeIdColumn = FindColumnName(result, "fieldTypeId", "FieldTypeId", "fieldtypeid"); Dictionary fieldUsage = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (DataRow schemeRow in schemeControls.Rows) { string sourceFieldName = GetSourceValue(schemeRow, "FieldName"); if (string.IsNullOrWhiteSpace(sourceFieldName)) continue; DataRow sourceRow = GetMatchedFieldConfigRow(sourceTable, sourceFieldName); if (sourceRow == null) continue; int usageNo; fieldUsage.TryGetValue(sourceFieldName, out usageNo); usageNo++; fieldUsage[sourceFieldName] = usageNo; string runtimeFieldName = GetRuntimeFieldName(sourceFieldName, usageNo); DataRow viewRow = result.NewRow(); foreach (DataColumn column in result.Columns) { if (sourceRow.Table.Columns.Contains(column.ColumnName)) { viewRow[column.ColumnName] = sourceRow[column.ColumnName]; } } NormalizeMyControlConfigRow(viewRow); int fieldTypeId = GetFieldTypeId(viewRow); FieldDesignItem viewItem = new FieldDesignItem { UserName = GetViewUserName(sourceRow, schemeRow), FieldName = sourceFieldName, RuntimeFieldName = runtimeFieldName, FieldTypeId = fieldTypeId, ControlWidth = ToPositiveInt(GetSourceValue(schemeRow, "ControlWidth"), DesignFieldControlWidth), ControlHeight = ToPositiveInt(GetSourceValue(schemeRow, "ControlHeight"), DesignFieldControlHeight) }; if (string.IsNullOrWhiteSpace(viewItem.UserName)) { viewItem.UserName = sourceFieldName; } NormalizeViewControlLayoutRow(viewRow, viewItem); SetFieldTypeIdValue(viewRow, fieldTypeIdColumn, viewItem.FieldTypeId); SetDataRowValue(viewRow, userNameColumn, viewItem.UserName); SetDataRowValue(viewRow, fieldNameColumn, runtimeFieldName); result.Rows.Add(viewRow); this._viewSchemeItems.Add(viewItem); } return result; } private void NormalizeViewControlLayoutRow(DataRow row, FieldDesignItem item) { if (row == null) return; SetDataRowValue(row, FindColumnName(row.Table, "controlLeft"), 0); SetDataRowValue(row, FindColumnName(row.Table, "controlTop"), 0); SetDataRowValue(row, FindColumnName(row.Table, "controlWidth"), item != null && item.ControlWidth > 0 ? item.ControlWidth : DesignFieldControlWidth); SetDataRowValue(row, FindColumnName(row.Table, "controlHeight"), item != null && item.ControlHeight > 0 ? item.ControlHeight : DesignFieldControlHeight); } private void PrepareMyControlConfigTable(DataTable table) { if (table == null) return; EnsureMyControlColumn(table, "id", typeof(string), string.Empty); EnsureMyControlColumn(table, "controlLeft", typeof(int), 0); EnsureMyControlColumn(table, "controlTop", typeof(int), 0); EnsureMyControlColumn(table, "controlWidth", typeof(int), 220); EnsureMyControlColumn(table, "controlHeight", typeof(int), 26); EnsureMyControlColumn(table, "edited", typeof(string), "0"); EnsureMyControlColumn(table, "nullable", typeof(bool), false); EnsureMyControlColumn(table, "fieldTypeId", typeof(string), "0"); EnsureMyControlColumn(table, "fieldName", typeof(string), string.Empty); EnsureMyControlColumn(table, "userName", typeof(string), string.Empty); EnsureMyControlColumn(table, "defaultValue", typeof(string), string.Empty); EnsureMyControlColumn(table, "lookupResult", typeof(string), string.Empty); EnsureMyControlColumn(table, "lookupKeyField", typeof(string), string.Empty); EnsureMyControlColumn(table, "lookupSql", typeof(string), string.Empty); } private void EnsureMyControlColumn(DataTable table, string columnName, Type dataType, object defaultValue) { if (table == null || !string.IsNullOrWhiteSpace(FindColumnName(table, columnName))) return; DataColumn column = new DataColumn(columnName, dataType); column.DefaultValue = defaultValue; table.Columns.Add(column); } private void NormalizeMyControlConfigRow(DataRow row) { if (row == null) return; SetDefaultRowValueIfEmpty(row, "controlWidth", 220); SetDefaultRowValueIfEmpty(row, "controlHeight", 26); SetDefaultRowValueIfEmpty(row, "controlLeft", 0); SetDefaultRowValueIfEmpty(row, "controlTop", 0); SetDefaultRowValueIfEmpty(row, "edited", "0"); SetDefaultRowValueIfEmpty(row, "nullable", false); NormalizeMyControlAliasValues(row); NormalizeBooleanRowValue(row, "nullable"); NormalizeFieldTypeIdRowValue(row); SetDefaultRowValueIfEmpty(row, "fieldTypeId", "0"); SetDefaultRowValueIfEmpty(row, "defaultValue", string.Empty); SetDefaultRowValueIfEmpty(row, "lookupResult", string.Empty); SetDefaultRowValueIfEmpty(row, "lookupKeyField", string.Empty); SetDefaultRowValueIfEmpty(row, "lookupSql", string.Empty); } private void NormalizeMyControlAliasValues(DataRow row) { if (row == null) return; SetRowValueFromAliases(row, "fieldName", "fieldname", "FieldName", "controlName", "ControlName"); SetRowValueFromAliases(row, "userName", "username", "username1", "UserName", "sysname", "SysName", "controlLabel", "ControlLabel"); SetRowValueFromAliases(row, "defaultValue", "defaultValue", "defaultdate", "DefaultDate"); SetRowValueFromAliases(row, "lookupResult", "lookupResult", "fieldsqlname", "fieldSqlName", "resultField", "ResultField"); SetRowValueFromAliases(row, "lookupKeyField", "lookupKeyField", "fieldsqlid", "fieldSqlId", "keyField", "KeyField"); SetRowValueFromAliases(row, "lookupSql", "lookupSql", "fieldsql", "fieldSql", "sourceSql", "SourceSql"); SetRowValueFromAliases(row, "nullable", true, "nullable", "CanNull", "canNull"); } private void SetRowValueFromAliases(DataRow row, string targetColumnName, params string[] sourceColumnNames) { SetRowValueFromAliases(row, targetColumnName, false, sourceColumnNames); } private void SetRowValueFromAliases(DataRow row, string targetColumnName, bool overwriteTarget, params string[] sourceColumnNames) { if (row == null || sourceColumnNames == null) return; string targetColumn = FindColumnName(row.Table, targetColumnName); if (string.IsNullOrWhiteSpace(targetColumn) || !overwriteTarget && !IsEmptyRowValue(row[targetColumn])) return; foreach (string sourceColumnName in sourceColumnNames) { string sourceColumn = FindColumnName(row.Table, sourceColumnName); if (string.IsNullOrWhiteSpace(sourceColumn) || string.Equals(sourceColumn, targetColumn, StringComparison.OrdinalIgnoreCase)) continue; object value = row[sourceColumn]; if (IsEmptyRowValue(value)) continue; SetDataRowValue(row, targetColumn, value); return; } } private bool IsEmptyRowValue(object value) { return value == null || value == DBNull.Value || string.IsNullOrWhiteSpace(value + ""); } private void SetDefaultRowValueIfEmpty(DataRow row, string columnName, object defaultValue) { string actualColumnName = FindColumnName(row.Table, columnName); if (string.IsNullOrWhiteSpace(actualColumnName)) return; object value = row[actualColumnName]; if (value == null || value == DBNull.Value || string.IsNullOrWhiteSpace(value + "") || "0".Equals(value + "") && ("controlWidth".Equals(columnName) || "controlHeight".Equals(columnName))) { SetDataRowValue(row, actualColumnName, defaultValue); } } private void NormalizeBooleanRowValue(DataRow row, string columnName) { string actualColumnName = FindColumnName(row.Table, columnName); if (string.IsNullOrWhiteSpace(actualColumnName)) return; string value = row[actualColumnName] + ""; DataColumn column = row.Table.Columns[actualColumnName]; if ("0".Equals(value)) { SetDataRowValue(row, actualColumnName, GetBooleanColumnValue(column, false)); } else if ("1".Equals(value)) { SetDataRowValue(row, actualColumnName, GetBooleanColumnValue(column, true)); } } private object GetBooleanColumnValue(DataColumn column, bool value) { if (column == null) return value; if (column.DataType == typeof(string)) return value ? "True" : "False"; if (column.DataType == typeof(int) || column.DataType == typeof(short) || column.DataType == typeof(long) || column.DataType == typeof(byte)) return value ? 1 : 0; return value; } private void NormalizeFieldTypeIdRowValue(DataRow row) { int fieldTypeId = GetFieldTypeId(row); if (fieldTypeId <= 0) return; SetFieldTypeIdValue(row, FindColumnName(row.Table, "fieldTypeId", "FieldTypeId", "fieldtypeid"), fieldTypeId); } private void SetFieldTypeIdValue(DataRow row, string columnName, int fieldTypeId) { if (row == null || fieldTypeId < 0 || string.IsNullOrWhiteSpace(columnName) || !row.Table.Columns.Contains(columnName)) return; DataColumn column = row.Table.Columns[columnName]; SetDataRowValue(row, columnName, GetIntColumnValue(column, fieldTypeId)); } private object GetIntColumnValue(DataColumn column, int value) { if (column == null) return value; if (column.DataType == typeof(string)) return value + ""; try { return Convert.ChangeType(value, column.DataType); } catch { return value; } } private DataRow GetMatchedFieldConfigRow(DataTable sourceTable, string fieldName) { if (string.IsNullOrWhiteSpace(fieldName) || sourceTable == null) return null; string fieldNameColumn = FindColumnName(sourceTable, "fieldname", "fieldName", "FieldName"); if (string.IsNullOrWhiteSpace(fieldNameColumn)) return null; foreach (DataRow row in sourceTable.Rows) { if (string.Equals(GetSourceValue(row, fieldNameColumn), fieldName, StringComparison.OrdinalIgnoreCase)) { return row; } } return null; } private string GetRuntimeFieldName(string fieldName, int usageNo) { return usageNo <= 1 ? fieldName : string.Format("{0}__Code{1:00}", fieldName, usageNo); } private void SetDataRowValue(DataRow row, string columnName, object value) { if (row == null || string.IsNullOrWhiteSpace(columnName) || !row.Table.Columns.Contains(columnName)) return; DataColumn column = row.Table.Columns[columnName]; bool readOnly = column.ReadOnly; try { column.ReadOnly = false; row[columnName] = value; } finally { column.ReadOnly = readOnly; } } private void ApplyCurrentRowValuesToViewControls() { if (this._viewControlObj == null || this.Model == null) return; DataRow currentRow = this.Model.GetMaintabFocusedRow(); if (currentRow == null) return; foreach (FieldDesignItem item in this._viewSchemeItems) { if (item == null || string.IsNullOrWhiteSpace(item.RuntimeFieldName) || string.IsNullOrWhiteSpace(item.FieldName)) continue; if (!currentRow.Table.Columns.Contains(item.FieldName)) continue; this._viewControlObj.SetControlValue(item.RuntimeFieldName, currentRow[item.FieldName]); } } private void RegisterViewControlValueChanged(System.Windows.Forms.Control parent) { if (parent == null) return; parent.TextChanged -= OnViewControlValueChanged; parent.TextChanged += OnViewControlValueChanged; DevExpress.XtraEditors.BaseEdit editor = parent as DevExpress.XtraEditors.BaseEdit; if (editor != null) { editor.EditValueChanged -= OnViewControlEditValueChanged; editor.EditValueChanged += OnViewControlEditValueChanged; } foreach (System.Windows.Forms.Control child in parent.Controls) { RegisterViewControlValueChanged(child); } } private void OnViewControlDataSourceBindCallBack(object sender, EventArgs e) { ApplyCurrentRowValuesToViewControls(); ClearCodePreview(); } private void OnViewControlValueChanged(object sender, EventArgs e) { ClearCodePreview(); } private void OnViewControlEditValueChanged(object sender, EventArgs e) { ClearCodePreview(); } private void UpdateCodePreview() { ClearCodePreview(); } private void ClearCodePreview() { if (this.txtCodePreview == null || !IsViewMode()) return; this.txtCodePreview.Text = string.Empty; } private void SaveCurrentSchemeLayout() { if (this._currentSchemeNode == null) return; TreeNodeData nodeData = this._currentSchemeNode.Tag as TreeNodeData; if (nodeData == null || !NodeTypeScheme.Equals(nodeData.NodeType) || nodeData.SchemeId <= 0) return; SaveNumberRuleGrid(nodeData); } private bool SaveNumberRuleGrid(TreeNodeData nodeData) { if (!IsDesignMode()) return false; if (nodeData == null || !NodeTypeScheme.Equals(nodeData.NodeType)) return false; if (!EnsureNumberRuleGridReady()) return false; try { CodeSchemeStorage.EnsureRuleStorage(); if (nodeData.BindModule) { EnsureNumberRuleGridSourceTable(NumberRuleTableName, true); EnsureNumberRuleGridKeyColumns(NumberRuleTableName); FillNumberRuleGridKeyValues(nodeData); SaveBindModuleNumberRuleRows(nodeData); DeleteOppositeRuleRows(SchemeControlTableName, nodeData.SchemeId); BindNumberRuleGridRows(LoadNumberRuleSchemeRows(nodeData)); return true; } EnsureNumberRuleGridSourceTable(SchemeControlTableName, true); EnsureNumberRuleGridKeyColumns(SchemeControlTableName); FillNumberRuleGridKeyValues(nodeData); SaveOwnNumberRuleRows(nodeData); DeleteOppositeRuleRows(NumberRuleTableName, nodeData.SchemeId); BindNumberRuleGridRows(LoadNumberRuleSchemeRows(nodeData)); return true; } catch (Exception ex) { LogHelper.Instance.WriteError(ex); MessageUtil.Show("保存逻辑失败:" + ex.Message); return false; } } private string[] GetNumberRuleKeyColumnNames() { return new string[] { NumberRuleSchemeIdColumn, NumberRuleSchemeCodeColumn, NumberRuleSchemeNameColumn, NumberRuleMenuKeyColumn, NumberRuleBindModuleColumn, NumberRuleBindModuleCodeColumn, NumberRuleModIdColumn }; } private string[] GetNumberRuleKeyColumnNames(string tableName) { if (!string.Equals(tableName, NumberRuleTableName, StringComparison.OrdinalIgnoreCase)) { return GetNumberRuleKeyColumnNames(); } return GetNumberRuleKeyColumnNames() .Where(n => CodeSchemeStorage.ColumnExists(NumberRuleTableName, n)) .ToArray(); } private DataTable GetNumberRuleGridDataSource() { GridControlEx grid = DesignRuleGrid; return grid == null || grid.GridControl == null ? null : grid.GridControl.DataSource as DataTable; } private void EnsureNumberRuleGridKeyColumns() { DataTable table = GetNumberRuleGridDataSource(); if (table == null) return; EnsureNumberRuleDataTableKeyColumns(table, GetNumberRuleSourceTable(table)); } private void EnsureNumberRuleGridKeyColumns(string tableName) { DataTable table = GetNumberRuleGridDataSource(); if (table == null) return; EnsureNumberRuleDataTableKeyColumns(table, tableName); } private void EnsureNumberRuleDataTableKeyColumns(DataTable table) { EnsureNumberRuleDataTableKeyColumns(table, GetNumberRuleSourceTable(table)); } private void EnsureNumberRuleDataTableKeyColumns(DataTable table, string tableName) { if (table == null) return; foreach (string columnName in GetNumberRuleKeyColumnNames(tableName)) { Type dataType = columnName == NumberRuleSchemeIdColumn ? typeof(int) : columnName == NumberRuleBindModuleColumn ? typeof(bool) : typeof(string); EnsureDataColumn(table, columnName, dataType); } } private void EnsureDataColumn(DataTable table, string columnName, Type dataType) { if (table == null || string.IsNullOrWhiteSpace(columnName) || table.Columns.Contains(columnName)) return; table.Columns.Add(columnName, dataType); } private void FillNumberRuleGridKeyValues(TreeNodeData nodeData) { DataTable table = GetNumberRuleGridDataSource(); if (table == null || nodeData == null) return; string bindModuleCode = nodeData.BindModule ? nodeData.BindModuleCode : string.Empty; string modid = nodeData.BindModule ? bindModuleCode : string.Empty; foreach (DataRow row in table.Rows) { if (row.RowState == DataRowState.Deleted) continue; SetRowValueIfColumnExists(row, NumberRuleSchemeIdColumn, nodeData.SchemeId); SetRowValueIfColumnExists(row, NumberRuleSchemeCodeColumn, nodeData.SchemeCode); SetRowValueIfColumnExists(row, NumberRuleSchemeNameColumn, nodeData.SchemeName); SetRowValueIfColumnExists(row, NumberRuleMenuKeyColumn, nodeData.MenuKey); SetRowValueIfColumnExists(row, NumberRuleBindModuleColumn, nodeData.BindModule); SetRowValueIfColumnExists(row, NumberRuleBindModuleCodeColumn, bindModuleCode); SetRowValueIfColumnExists(row, NumberRuleModIdColumn, modid); if (row.Table.Columns.Contains(DesignRuleUseColumn) && string.IsNullOrWhiteSpace(row[DesignRuleUseColumn] + "")) { SetRowValueIfColumnExists(row, DesignRuleUseColumn, true); } } } private void SetRowValueIfColumnExists(DataRow row, string columnName, object value) { if (row == null || row.Table == null || !row.Table.Columns.Contains(columnName)) return; DataColumn column = row.Table.Columns[columnName]; object nextValue = GetDataColumnValue(column, value); object currentValue = row[columnName]; if (string.Equals(currentValue + "", nextValue + "", StringComparison.Ordinal)) return; bool readOnly = column.ReadOnly; try { column.ReadOnly = false; row[columnName] = nextValue ?? DBNull.Value; } finally { column.ReadOnly = readOnly; } } private object GetDataColumnValue(DataColumn column, object value) { if (value == null || value == DBNull.Value) return DBNull.Value; if (column == null) return value; if (column.DataType == typeof(bool)) return ToBool(value); if (column.DataType == typeof(string)) return value + ""; try { return Convert.ChangeType(value, column.DataType); } catch { return value; } } private bool HasModifiedNumberRuleRows() { DataTable table = GetNumberRuleGridDataSource(); if (table == null) return false; return table.Rows.Cast().Any(n => n.RowState == DataRowState.Added || n.RowState == DataRowState.Modified || n.RowState == DataRowState.Deleted); } private bool HasPendingSchemeChanges() { if (this._currentSchemeNode == null) return false; TreeNodeData nodeData = this._currentSchemeNode.Tag as TreeNodeData; if (nodeData == null || !NodeTypeScheme.Equals(nodeData.NodeType)) return false; return HasModifiedNumberRuleRows(); } private void CommitDesignRuleGridEditor() { GridControlEx grid = DesignRuleGrid; if (grid == null || grid.GridView == null) return; try { grid.GridView.PostEditor(); grid.GridView.UpdateCurrentRow(); } catch (Exception ex) { LogHelper.Instance.WriteError(ex); } } private bool DeleteSelectedNumberRuleRows() { GridControlEx grid = DesignRuleGrid; if (grid == null || grid.GridView == null) return false; CommitDesignRuleGridEditor(); List selectedRows = GetSelectedNumberRuleRows(grid); if (selectedRows.Count == 0) { MessageUtil.Show("请先选择要删除的数据。"); return false; } string confirmText = selectedRows.Count == 1 ? "确定删除当前选中的数据吗?" : string.Format("确定删除当前选中的 {0} 条数据吗?", selectedRows.Count); DialogResult result = MessageUtil.Show(confirmText, MessageBoxButtons.YesNo); if (result != DialogResult.Yes) return false; foreach (DataRow row in selectedRows) { if (row == null || row.RowState == DataRowState.Deleted || row.RowState == DataRowState.Detached) continue; row.Delete(); } grid.GridView.ClearSelection(); grid.GridView.RefreshData(); return true; } private List GetSelectedNumberRuleRows(GridControlEx grid) { List result = new List(); if (grid == null || grid.GridView == null) return result; int[] rowHandles = grid.GridView.GetSelectedRows(); if (rowHandles != null) { foreach (int rowHandle in rowHandles) { AddNumberRuleRowByHandle(grid, rowHandle, result); } } if (result.Count == 0) { AddNumberRuleRowByHandle(grid, grid.GridView.FocusedRowHandle, result); } return result; } private void AddNumberRuleRowByHandle(GridControlEx grid, int rowHandle, List rows) { if (grid == null || grid.GridView == null || rows == null || rowHandle < 0) return; DataRow row = grid.GridView.GetDataRow(rowHandle); if (row == null || row.RowState == DataRowState.Deleted || row.RowState == DataRowState.Detached) return; if (rows.Contains(row)) return; rows.Add(row); } private void SaveBindModuleNumberRuleRows(TreeNodeData nodeData) { DataTable source = GetNumberRuleGridDataSource(); if (source == null || nodeData == null || string.IsNullOrWhiteSpace(nodeData.BindModuleCode)) return; DeleteBindModuleNumberRuleRows(nodeData.BindModuleCode); DataTable dbColumns = BaseImpl.GetTableColumns(NumberRuleTableName); string autogrowColumn = MainImpl.GetAutogrowcolumn(NumberRuleTableName); foreach (DataRow row in source.Rows) { if (row.RowState == DataRowState.Deleted) continue; if (IsEmptyNumberRuleRow(row)) continue; InsertRuleRow(NumberRuleTableName, row, dbColumns, autogrowColumn); } source.AcceptChanges(); } private void SaveOwnNumberRuleRows(TreeNodeData nodeData) { DataTable source = GetNumberRuleGridDataSource(); if (source == null || nodeData == null || nodeData.SchemeId <= 0) return; DeleteRuleRows(SchemeControlTableName, nodeData.SchemeId); DataTable dbColumns = BaseImpl.GetTableColumns(SchemeControlTableName); string autogrowColumn = MainImpl.GetAutogrowcolumn(SchemeControlTableName); foreach (DataRow row in source.Rows) { if (row.RowState == DataRowState.Deleted) continue; if (IsEmptyNumberRuleRow(row)) continue; InsertRuleRow(SchemeControlTableName, row, dbColumns, autogrowColumn); } source.AcceptChanges(); } private void SoftDeleteRuleRows(string tableName, int schemeId) { if (schemeId <= 0 || string.IsNullOrWhiteSpace(tableName) || !CodeSchemeStorage.TableExists(tableName) || !CodeSchemeStorage.ColumnExists(tableName, NumberRuleSchemeIdColumn)) return; if (CodeSchemeStorage.ColumnExists(tableName, DesignRuleUseColumn)) { string sql = string.Format("UPDATE {0} SET {1} = 0 WHERE {2} = @SchemeId", CodeSchemeStorage.QuoteSqlIdentifier(tableName), CodeSchemeStorage.QuoteSqlIdentifier(DesignRuleUseColumn), CodeSchemeStorage.QuoteSqlIdentifier(NumberRuleSchemeIdColumn)); SqlHelper.ExecuteNonQuery(CommandType.Text, sql, new SqlParameter[] { new SqlParameter("@SchemeId", schemeId) }); return; } string deleteSql = string.Format("DELETE FROM {0} WHERE {1} = @SchemeId", CodeSchemeStorage.QuoteSqlIdentifier(tableName), CodeSchemeStorage.QuoteSqlIdentifier(NumberRuleSchemeIdColumn)); SqlHelper.ExecuteNonQuery(CommandType.Text, deleteSql, new SqlParameter[] { new SqlParameter("@SchemeId", schemeId) }); } private void DeleteRuleRows(string tableName, int schemeId) { if (schemeId <= 0 || string.IsNullOrWhiteSpace(tableName) || !CodeSchemeStorage.TableExists(tableName) || !CodeSchemeStorage.ColumnExists(tableName, NumberRuleSchemeIdColumn)) return; string sql = string.Format("DELETE FROM {0} WHERE {1} = @SchemeId", CodeSchemeStorage.QuoteSqlIdentifier(tableName), CodeSchemeStorage.QuoteSqlIdentifier(NumberRuleSchemeIdColumn)); SqlHelper.ExecuteNonQuery(CommandType.Text, sql, new SqlParameter[] { new SqlParameter("@SchemeId", schemeId) }); } private void DeleteOppositeRuleRows(string tableName, int schemeId) { if (!RuleRowsExist(tableName, schemeId)) return; DeleteRuleRows(tableName, schemeId); } private bool RuleRowsExist(string tableName, int schemeId) { if (schemeId <= 0 || string.IsNullOrWhiteSpace(tableName) || !CodeSchemeStorage.TableExists(tableName) || !CodeSchemeStorage.ColumnExists(tableName, NumberRuleSchemeIdColumn)) return false; string sql = string.Format("SELECT COUNT(1) FROM {0} WHERE {1} = @SchemeId", CodeSchemeStorage.QuoteSqlIdentifier(tableName), CodeSchemeStorage.QuoteSqlIdentifier(NumberRuleSchemeIdColumn)); object result = SqlHelper.ExecuteScalar(CommandType.Text, sql, new SqlParameter[] { new SqlParameter("@SchemeId", schemeId) }); return ToInt(result) > 0; } private bool BindModuleNumberRulesExist(string bindModuleCode) { if (string.IsNullOrWhiteSpace(bindModuleCode) || !CodeSchemeStorage.TableExists(NumberRuleTableName)) return false; List moduleConditions = new List(); if (CodeSchemeStorage.ColumnExists(NumberRuleTableName, NumberRuleModIdColumn)) { moduleConditions.Add(string.Format("ISNULL(CONVERT(NVARCHAR(100), {0}), '') = @BindModuleCode", CodeSchemeStorage.QuoteSqlIdentifier(NumberRuleModIdColumn))); } if (CodeSchemeStorage.ColumnExists(NumberRuleTableName, NumberRuleBindModuleCodeColumn)) { moduleConditions.Add(string.Format("ISNULL(CONVERT(NVARCHAR(100), {0}), '') = @BindModuleCode", CodeSchemeStorage.QuoteSqlIdentifier(NumberRuleBindModuleCodeColumn))); } if (moduleConditions.Count == 0) return false; string useCondition = CodeSchemeStorage.ColumnExists(NumberRuleTableName, DesignRuleUseColumn) ? string.Format(" AND ISNULL({0}, 1) = 1", CodeSchemeStorage.QuoteSqlIdentifier(DesignRuleUseColumn)) : string.Empty; string sql = string.Format("SELECT COUNT(1) FROM {0} WHERE ({1}){2}", CodeSchemeStorage.QuoteSqlIdentifier(NumberRuleTableName), string.Join(" OR ", moduleConditions), useCondition); object result = SqlHelper.ExecuteScalar(CommandType.Text, sql, new SqlParameter[] { new SqlParameter("@BindModuleCode", bindModuleCode) }); return ToInt(result) > 0; } private bool BindModuleOwnedByOtherScheme(string bindModuleCode, int currentSchemeId, out string ownerSchemeName) { ownerSchemeName = string.Empty; if (string.IsNullOrWhiteSpace(bindModuleCode) || !CodeSchemeStorage.TableExists(SchemeTableName)) return false; string sql = @" SELECT TOP 1 SchemeName FROM P_CodeSchemeTab WHERE ISNULL(BindModule, 0) = 1 AND ISNULL(BindModuleCode, '') = @BindModuleCode AND SchemeId <> @SchemeId ORDER BY SchemeId"; object result = SqlHelper.ExecuteScalar(CommandType.Text, sql, new SqlParameter[] { new SqlParameter("@BindModuleCode", bindModuleCode), new SqlParameter("@SchemeId", currentSchemeId) }); ownerSchemeName = result == null || result == DBNull.Value ? string.Empty : result + ""; if (string.IsNullOrWhiteSpace(ownerSchemeName)) ownerSchemeName = "未命名方案"; return result != null && result != DBNull.Value; } private void DeleteBindModuleNumberRuleRows(string bindModuleCode) { if (string.IsNullOrWhiteSpace(bindModuleCode) || !CodeSchemeStorage.TableExists(NumberRuleTableName)) return; List moduleConditions = new List(); if (CodeSchemeStorage.ColumnExists(NumberRuleTableName, NumberRuleModIdColumn)) { moduleConditions.Add(string.Format("ISNULL(CONVERT(NVARCHAR(100), {0}), '') = @BindModuleCode", CodeSchemeStorage.QuoteSqlIdentifier(NumberRuleModIdColumn))); } if (CodeSchemeStorage.ColumnExists(NumberRuleTableName, NumberRuleBindModuleCodeColumn)) { moduleConditions.Add(string.Format("ISNULL(CONVERT(NVARCHAR(100), {0}), '') = @BindModuleCode", CodeSchemeStorage.QuoteSqlIdentifier(NumberRuleBindModuleCodeColumn))); } if (moduleConditions.Count == 0) return; string sql = string.Format("DELETE FROM {0} WHERE ({1})", CodeSchemeStorage.QuoteSqlIdentifier(NumberRuleTableName), string.Join(" OR ", moduleConditions)); SqlHelper.ExecuteNonQuery(CommandType.Text, sql, new SqlParameter[] { new SqlParameter("@BindModuleCode", bindModuleCode) }); } private bool IsEmptyNumberRuleRow(DataRow row) { if (row == null || row.RowState == DataRowState.Deleted) return true; foreach (DataColumn column in row.Table.Columns) { if (IsNumberRuleSystemColumn(column.ColumnName)) continue; if (!string.IsNullOrWhiteSpace(row[column] + "")) return false; } return true; } private bool IsNumberRuleSystemColumn(string columnName) { if (IsNumberRuleKeyColumn(columnName)) return true; string[] systemColumns = { "ID", "Id", "id", DesignRuleUseColumn, DesignRuleSortColumn, "CreateUserId", "CreateUserName", "CreateTime", "ModifyUserId", "ModifyUserName", "ModifyTime" }; return systemColumns.Any(n => string.Equals(n, columnName, StringComparison.OrdinalIgnoreCase)); } private bool IsNumberRuleKeyColumn(string columnName) { return GetNumberRuleKeyColumnNames().Any(n => string.Equals(n, columnName, StringComparison.OrdinalIgnoreCase)); } private void InsertRuleRow(string tableName, DataRow row, DataTable dbColumns, string autogrowColumn) { if (string.IsNullOrWhiteSpace(tableName) || row == null || dbColumns == null) return; List fields = new List(); List values = new List(); List parameters = new List(); int parameterIndex = 0; foreach (DataColumn dbColumn in dbColumns.Columns) { string columnName = dbColumn.ColumnName; if (string.Equals(columnName, autogrowColumn, StringComparison.OrdinalIgnoreCase)) continue; if (row.Table == null || !row.Table.Columns.Contains(columnName)) continue; if (IsEmptyRowValue(row[columnName])) continue; string parameterName = "@P" + parameterIndex++; fields.Add(CodeSchemeStorage.QuoteSqlIdentifier(columnName)); values.Add(parameterName); parameters.Add(new SqlParameter(parameterName, GetDbColumnValue(row[columnName], dbColumn.DataType))); } if (fields.Count == 0) return; string sql = string.Format("INSERT INTO {0}({1}) VALUES({2})", CodeSchemeStorage.QuoteSqlIdentifier(tableName), string.Join(",", fields), string.Join(",", values)); SqlHelper.ExecuteNonQuery(CommandType.Text, sql, parameters.ToArray()); } private object GetDbColumnValue(object value, Type dataType) { if (value == null || value == DBNull.Value) return DBNull.Value; string text = value + ""; if (string.IsNullOrWhiteSpace(text)) { if (dataType == typeof(string)) return string.Empty; if (dataType == typeof(DateTime)) return DBNull.Value; if (dataType == typeof(bool)) return false; if (dataType == typeof(decimal) || dataType == typeof(double) || dataType == typeof(float) || dataType == typeof(int) || dataType == typeof(long) || dataType == typeof(short) || dataType == typeof(byte)) { return 0; } return DBNull.Value; } if (dataType == typeof(bool)) return ToBool(value); try { return Convert.ChangeType(value, dataType); } catch { return value; } } private DataTable LoadNumberRuleSchemeRows(TreeNodeData nodeData) { CodeSchemeStorage.EnsureRuleStorage(); string tableName = GetRuleTableName(nodeData); DataTable table; if (nodeData == null || nodeData.SchemeId <= 0) { table = CreateEmptyNumberRuleTable(tableName); table.AcceptChanges(); return table; } List parameters = new List(); string whereSql = GetRuleTableWhereSql(tableName, nodeData, parameters); if (string.IsNullOrWhiteSpace(whereSql)) { table = CreateEmptyNumberRuleTable(tableName); table.AcceptChanges(); return table; } string useCondition = CodeSchemeStorage.ColumnExists(tableName, DesignRuleUseColumn) ? string.Format(" AND ISNULL({0}, 1) = 1", CodeSchemeStorage.QuoteSqlIdentifier(DesignRuleUseColumn)) : string.Empty; string sql = string.Format("SELECT * FROM {0} WHERE {1}{2}{3}", CodeSchemeStorage.QuoteSqlIdentifier(tableName), whereSql, useCondition, GetNumberRuleOrderByClause(tableName)); table = SqlHelper.ExecuteDataTable(sql, parameters.ToArray()); if (table == null) table = CreateEmptyNumberRuleTable(tableName); EnsureNumberRuleDataTableKeyColumns(table, tableName); SetNumberRuleSourceTable(table, tableName); table.AcceptChanges(); return table; } private string GetRuleTableWhereSql(string tableName, TreeNodeData nodeData, List parameters) { if (string.IsNullOrWhiteSpace(tableName) || nodeData == null) return string.Empty; if (!string.Equals(tableName, NumberRuleTableName, StringComparison.OrdinalIgnoreCase)) { if (!CodeSchemeStorage.ColumnExists(tableName, NumberRuleSchemeIdColumn) || nodeData.SchemeId <= 0) return string.Empty; if (parameters != null) parameters.Add(new SqlParameter("@SchemeId", nodeData.SchemeId)); return string.Format("{0} = @SchemeId", CodeSchemeStorage.QuoteSqlIdentifier(NumberRuleSchemeIdColumn)); } string bindModuleCode = nodeData.BindModuleCode; if (IsDesignMode() && this.chkBindModule.Checked) { string selectedModuleCode = GetSelectedBindModuleCode(); if (!string.IsNullOrWhiteSpace(selectedModuleCode)) bindModuleCode = selectedModuleCode; } if (string.IsNullOrWhiteSpace(bindModuleCode)) return string.Empty; List moduleConditions = new List(); if (CodeSchemeStorage.ColumnExists(NumberRuleTableName, NumberRuleModIdColumn)) { moduleConditions.Add(string.Format("ISNULL(CONVERT(NVARCHAR(100), {0}), '') = @BindModuleCode", CodeSchemeStorage.QuoteSqlIdentifier(NumberRuleModIdColumn))); } if (CodeSchemeStorage.ColumnExists(NumberRuleTableName, NumberRuleBindModuleCodeColumn)) { moduleConditions.Add(string.Format("ISNULL(CONVERT(NVARCHAR(100), {0}), '') = @BindModuleCode", CodeSchemeStorage.QuoteSqlIdentifier(NumberRuleBindModuleCodeColumn))); } if (moduleConditions.Count == 0) return string.Empty; if (parameters != null) parameters.Add(new SqlParameter("@BindModuleCode", bindModuleCode)); return "(" + string.Join(" OR ", moduleConditions) + ")"; } private bool EnsureNumberRuleGridSourceTable(string tableName, bool markRowsAdded) { if (string.IsNullOrWhiteSpace(tableName)) return false; DataTable source = GetNumberRuleGridDataSource(); if (source == null) { BindNumberRuleGridRows(CreateEmptyNumberRuleTable(tableName)); return true; } string sourceTableName = GetNumberRuleSourceTable(source); if (string.Equals(sourceTableName, tableName, StringComparison.OrdinalIgnoreCase)) { return false; } BindNumberRuleGridRows(ConvertNumberRuleRowsToTable(source, tableName, markRowsAdded)); return true; } private DataTable ConvertNumberRuleRowsToTable(DataTable source, string tableName, bool markRowsAdded) { DataTable target = CreateEmptyNumberRuleTable(tableName); string autogrowColumn = MainImpl.GetAutogrowcolumn(tableName); if (source != null) { foreach (DataRow sourceRow in source.Rows) { if (sourceRow.RowState == DataRowState.Deleted || IsEmptyNumberRuleRow(sourceRow)) continue; DataRow targetRow = target.NewRow(); foreach (DataColumn targetColumn in target.Columns) { string columnName = targetColumn.ColumnName; if (!string.IsNullOrWhiteSpace(autogrowColumn) && string.Equals(columnName, autogrowColumn, StringComparison.OrdinalIgnoreCase)) { continue; } if (!source.Columns.Contains(columnName)) continue; object value = sourceRow[columnName]; if (value == DBNull.Value) continue; targetRow[columnName] = GetDbColumnValue(value, targetColumn.DataType); } target.Rows.Add(targetRow); } } SetNumberRuleSourceTable(target, tableName); if (!markRowsAdded) { target.AcceptChanges(); } return target; } private void SetNumberRuleSourceTable(DataTable table, string tableName) { if (table == null) return; table.TableName = string.IsNullOrWhiteSpace(tableName) ? string.Empty : tableName; table.ExtendedProperties[NumberRuleSourceTableProperty] = table.TableName; } private string GetNumberRuleSourceTable(DataTable table) { if (table == null) return string.Empty; object value = table.ExtendedProperties[NumberRuleSourceTableProperty]; if (!string.IsNullOrWhiteSpace(value + "")) return value + ""; return table.TableName; } private string GetRuleTableName(TreeNodeData nodeData) { return IsSchemeBindModule(nodeData) ? NumberRuleTableName : SchemeControlTableName; } private bool IsSchemeBindModule(TreeNodeData nodeData) { if (IsDesignMode()) { return this.chkBindModule.Checked; } return nodeData != null && nodeData.BindModule; } private DataTable CreateEmptyNumberRuleTable() { return CreateEmptyNumberRuleTable(NumberRuleTableName); } private DataTable CreateEmptyNumberRuleTable(string tableName) { DataTable table = BaseImpl.GetTableColumns(string.IsNullOrWhiteSpace(tableName) ? NumberRuleTableName : tableName); EnsureNumberRuleDataTableKeyColumns(table); SetNumberRuleSourceTable(table, string.IsNullOrWhiteSpace(tableName) ? NumberRuleTableName : tableName); return table; } private string GetNumberRuleOrderByClause(string tableName) { if (CodeSchemeStorage.ColumnExists(tableName, DesignRuleSortColumn)) { return " ORDER BY " + CodeSchemeStorage.QuoteSqlIdentifier(DesignRuleSortColumn); } if (CodeSchemeStorage.ColumnExists(tableName, "Orderid")) { return " ORDER BY " + CodeSchemeStorage.QuoteSqlIdentifier("Orderid"); } if (CodeSchemeStorage.ColumnExists(tableName, "ID")) { return " ORDER BY " + CodeSchemeStorage.QuoteSqlIdentifier("ID"); } if (CodeSchemeStorage.ColumnExists(tableName, "SchemeControlId")) { return " ORDER BY " + CodeSchemeStorage.QuoteSqlIdentifier("SchemeControlId"); } return string.Empty; } private void BindNumberRuleGridRows(DataTable table) { GridControlEx grid = DesignRuleGrid; if (grid == null) return; EnsureNumberRuleDataTableKeyColumns(table); this._loadingDesignRuleGrid = true; try { grid.SetGridViewDataSource(table ?? CreateEmptyNumberRuleTable(), false); ConfigureDesignRuleGridColumns(); } finally { this._loadingDesignRuleGrid = false; } } private bool EnsureNumberRuleGridReady() { try { InitializeNumberRuleGrid(); return true; } catch (Exception ex) { LogHelper.Instance.WriteError(ex); MessageUtil.Show("编码规则表格加载失败:" + ex.Message); return false; } } private void InitializeNumberRuleGridWithPrompt() { try { InitializeNumberRuleGrid(); } catch (Exception ex) { LogHelper.Instance.WriteError(ex); ClearDesignRuleGrid(); MessageUtil.Show("编码规则表格加载失败:" + ex.Message); } } private void InitializeNumberRuleGrid() { string moduleCode = GetNumberRuleGridModuleCode(); if (this._numberRuleGridInitialized && string.Equals(this._numberRuleGridModuleCode, moduleCode, StringComparison.OrdinalIgnoreCase)) { ApplyDesignRuleGridEditState(); return; } if (string.IsNullOrWhiteSpace(moduleCode)) { throw new InvalidOperationException("未获取到 ModuleCode,无法加载编码规则表格。"); } DataRow modelRow = MainImpl.GetSystemdllTab(moduleCode); if (modelRow == null) { throw new InvalidOperationException(string.Format("未找到模块[{0}]的系统配置。", moduleCode)); } ModuleModel sysModel = new ModuleModel(modelRow); EnsureNumberRuleMainTable(sysModel); this.gridDesignRules.VisibleOperPanel = false; this.gridDesignRules.VisibleSearchPanel = true; this.gridDesignRules.InitializeControl(sysModel, CreateNumberRuleGridModel(moduleCode)); this.gridDesignRules.HideTopToolPanel(); this._numberRuleGridInitialized = true; this._numberRuleGridModuleCode = moduleCode; ApplyDesignRuleGridEditState(); } private string GetNumberRuleGridModuleCode() { return this.Model == null ? string.Empty : this.Model.ModuleCode; } private DynamicModuleModel CreateNumberRuleGridModel(string moduleCode) { return new DynamicModuleModel(new string[] { this.Text, ERPInfo.Instance.UserId, ERPInfo.Instance.UserName, GetNumberRuleGridPrivilege(), moduleCode, GetNumberRuleGridModuleIdText(), moduleCode, string.Empty, string.Empty }); } private string GetNumberRuleGridPrivilege() { if (this.Model == null || string.IsNullOrWhiteSpace(this.Model.Privilege)) { return "1"; } return this.Model.Privilege; } private string GetNumberRuleGridModuleIdText() { return this.Model == null || this.Model.ModuleId <= 0 ? string.Empty : this.Model.ModuleId + ""; } private void EnsureNumberRuleMainTable(ModuleModel sysModel) { string tableName = sysModel == null ? string.Empty : (sysModel.MenuTable + "").Trim(); if (!string.Equals(tableName, NumberRuleTableName, StringComparison.OrdinalIgnoreCase)) { throw new InvalidOperationException(string.Format( "编码规则表格主表配置错误:当前为[{0}],必须为[{1}]。", string.IsNullOrWhiteSpace(tableName) ? "空" : tableName, NumberRuleTableName)); } CodeSchemeStorage.EnsureRuleStorage(); } private List GetUsedDesignRuleRows() { List result = new List(); if (this._designRuleTable == null) return result; result = this._designRuleTable.Rows.Cast() .Where(IsDesignRuleRowUsed) .OrderBy(n => ToPositiveInt(GetSourceValue(n, DesignRuleSortColumn), int.MaxValue)) .ThenBy(n => this._designRuleTable.Rows.IndexOf(n)) .ToList(); return result; } private bool IsDesignRuleRowUsed(DataRow row) { if (row == null || !row.Table.Columns.Contains(DesignRuleUseColumn)) return false; return ToBool(row[DesignRuleUseColumn]); } private void BindEmptyDesignRuleGrid() { InitializeNumberRuleGridWithPrompt(); BindNumberRuleGridRows(CreateEmptyNumberRuleTable(GetRuleTableName(null))); } private void ReloadCurrentSchemeDesignRules() { if (!IsDesignMode()) return; TreeNodeData nodeData = this._currentSchemeNode == null ? null : this._currentSchemeNode.Tag as TreeNodeData; if (nodeData == null || !NodeTypeScheme.Equals(nodeData.NodeType)) { InitializeNumberRuleGridWithPrompt(); return; } LoadSchemeDesignRules(null); } private void LoadSchemeDesignRules(DataTable schemeControls) { InitializeNumberRuleGridWithPrompt(); TreeNodeData nodeData = this._currentSchemeNode == null ? null : this._currentSchemeNode.Tag as TreeNodeData; if (schemeControls == null) { schemeControls = LoadNumberRuleSchemeRows(nodeData); } BindNumberRuleGridRows(schemeControls); } private DataTable LoadModuleLeftSourceTable(string moduleCode) { this._moduleLeftSourceRow = null; this._moduleLeftSourceTable = new DataTable(); if (string.IsNullOrWhiteSpace(moduleCode)) return this._moduleLeftSourceTable; try { this._moduleLeftSourceRow = BaseModuleImpl.GetBaseLeftTreeField(moduleCode); if (this._moduleLeftSourceRow != null) { string fieldSql = GetRowValue(this._moduleLeftSourceRow, "fieldsql"); if (!string.IsNullOrWhiteSpace(fieldSql)) { this._moduleLeftSourceTable = BaseImpl.GetDataTableResult(fieldSql); } } } catch (Exception ex) { LogHelper.Instance.WriteError(ex); this._moduleLeftSourceTable = new DataTable(); } return this._moduleLeftSourceTable; } private DataTable CreateDesignRuleTable() { DataTable table = new DataTable(); table.Columns.Add(DesignRuleUseColumn, typeof(int)); table.Columns.Add(DesignRuleSortColumn, typeof(int)); table.Columns.Add(DesignRuleUserNameColumn, typeof(string)); table.Columns.Add(DesignRuleFieldNameColumn, typeof(string)); table.Columns.Add(DesignRuleFieldTypeColumn, typeof(int)); return table; } private void AppendSavedDesignRuleRows(DataTable designTable, DataTable schemeControls) { if (designTable == null || schemeControls == null || schemeControls.Rows.Count == 0) return; HashSet usedSourceRows = new HashSet(); int defaultSort = 1; foreach (DataRow schemeRow in schemeControls.Rows) { string fieldName = GetSourceValue(schemeRow, "FieldName"); if (string.IsNullOrWhiteSpace(fieldName)) continue; DataRow sourceRow = GetMatchedFieldConfigRow(this._fieldConfigTable, fieldName); if (sourceRow != null) { usedSourceRows.Add(sourceRow); } AddDesignRuleRow(designTable, sourceRow, schemeRow, true, ToPositiveInt(GetSourceValue(schemeRow, "SortNo"), defaultSort)); defaultSort++; } designTable.ExtendedProperties["UsedSourceRows"] = usedSourceRows; } private void AppendAvailableDesignRuleRows(DataTable designTable) { if (designTable == null || this._fieldConfigTable == null) return; HashSet usedSourceRows = designTable.ExtendedProperties["UsedSourceRows"] as HashSet; int sortNo = designTable.Rows.Count + 1; foreach (DataRow sourceRow in this._fieldConfigTable.Rows) { if (usedSourceRows != null && usedSourceRows.Contains(sourceRow)) continue; string fieldName = GetSourceValue(sourceRow, FindColumnName(this._fieldConfigTable, "fieldname", "fieldName", "FieldName")); if (string.IsNullOrWhiteSpace(fieldName)) continue; AddDesignRuleRow(designTable, sourceRow, null, false, sortNo); sortNo++; } } private void AddDesignRuleRow(DataTable designTable, DataRow sourceRow, DataRow schemeRow, bool useEd, int sortNo) { if (designTable == null) return; string fieldName = GetSourceValue(sourceRow, FindColumnName(sourceRow == null ? null : sourceRow.Table, "fieldname", "fieldName", "FieldName")); if (string.IsNullOrWhiteSpace(fieldName)) { fieldName = GetSourceValue(schemeRow, "FieldName"); } if (string.IsNullOrWhiteSpace(fieldName)) return; DataRow row = designTable.NewRow(); row[DesignRuleUseColumn] = useEd ? 1 : 0; row[DesignRuleSortColumn] = sortNo <= 0 ? designTable.Rows.Count + 1 : sortNo; row[DesignRuleUserNameColumn] = GetViewUserName(sourceRow, schemeRow); if (string.IsNullOrWhiteSpace(row[DesignRuleUserNameColumn] + "")) { row[DesignRuleUserNameColumn] = fieldName; } row[DesignRuleFieldNameColumn] = fieldName; row[DesignRuleFieldTypeColumn] = GetFieldTypeId(sourceRow); designTable.Rows.Add(row); } private void BindDesignRuleGrid(DataTable table) { this._loadingDesignRuleGrid = true; try { GridControlEx grid = DesignRuleGrid; if (grid == null) return; string gridModuleCode = GetDesignRuleGridModuleCode(); DataTable gridColumns = LoadDesignRuleGridColumns(gridModuleCode); grid.SetEditColumns(gridColumns, GetDesignRuleGridCustomKey(gridModuleCode)); ApplyDesignRuleGridStyle(grid); grid.SetGridViewDataSource(table, false); ConfigureDesignRuleGridColumns(); } finally { this._loadingDesignRuleGrid = false; } } private DataTable LoadDesignRuleGridColumns(string moduleCode) { if (string.IsNullOrWhiteSpace(moduleCode)) { throw new InvalidOperationException("未获取到 ModuleCode,无法加载表格列配置。"); } DataTable gridColumns = BaseModuleImpl.GetBaseGridColumns(moduleCode); if (gridColumns == null || gridColumns.Rows.Count == 0) { throw new InvalidOperationException(string.Format("模块[{0}]未配置表格列。", moduleCode)); } return gridColumns; } private void ClearDesignRuleGrid() { GridControlEx grid = DesignRuleGrid; if (grid == null) return; if (grid.GridView != null) { grid.GridView.Columns.Clear(); } grid.SetGridViewDataSource(CreateDesignRuleTable(), false); } private string GetDesignRuleGridModuleCode() { if (this.Model != null && !string.IsNullOrWhiteSpace(this.Model.ModuleCode)) { return this.Model.ModuleCode; } return GetCurrentModuleCode(); } private string GetDesignRuleGridCustomKey(string moduleCode) { if (!string.IsNullOrWhiteSpace(moduleCode)) { try { DataRow modelRow = MainImpl.GetSystemdllTab(moduleCode); if (modelRow != null) { ModuleModel sysModel = new ModuleModel(modelRow); if (!string.IsNullOrWhiteSpace(sysModel.FormKey)) { return GridCustomColumnStruct.BaseMainGridView + sysModel.FormKey; } } } catch (Exception ex) { LogHelper.Instance.WriteError(ex); } } return GridCustomColumnStruct.BaseMainGridView + "CodeDesign_" + moduleCode; } private void ApplyDesignRuleGridStyle(GridControlEx grid) { if (grid == null || grid.GridView == null) return; if (SystemInfo.Instance.GridRowFontSize > 0) { grid.GridView.Appearance.Row.Font = new Font("微软雅黑", SystemInfo.Instance.GridRowFontSize); } if (SystemInfo.Instance.GridRowHeight > 0) { grid.GridView.ColumnPanelRowHeight = grid.GridView.RowHeight = SystemInfo.Instance.GridRowHeight; } } private void ConfigureDesignRuleGridColumns() { GridControlEx grid = DesignRuleGrid; if (grid == null || grid.GridView == null) return; ApplyDesignRuleGridEditState(); if (!IsDesignMode()) return; GridColumn useColumn = grid.GridView.Columns[DesignRuleUseColumn]; if (useColumn != null) { useColumn.OptionsColumn.AllowEdit = true; useColumn.OptionsColumn.ReadOnly = false; } GridColumn sortColumn = grid.GridView.Columns[DesignRuleSortColumn]; if (sortColumn != null) { sortColumn.OptionsColumn.AllowEdit = true; sortColumn.OptionsColumn.ReadOnly = false; } } private void ApplyDesignRuleGridEditState() { GridControlEx grid = DesignRuleGrid; if (grid == null || grid.GridView == null) return; bool designMode = IsDesignMode(); grid.GridView.OptionsBehavior.Editable = designMode; grid.GridView.OptionsBehavior.ReadOnly = !designMode; if (designMode) return; foreach (GridColumn column in grid.GridView.Columns) { column.OptionsColumn.AllowEdit = false; column.OptionsColumn.ReadOnly = true; } } private void OnDesignRuleCellValueChanging(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e) { if (this._loadingDesignRuleGrid || !IsDesignMode()) return; if (this._currentSchemeNode != null) { this._currentSchemeDirty = true; } if (e.Column != null && string.Equals(e.Column.FieldName, DesignRuleUseColumn, StringComparison.OrdinalIgnoreCase)) { GridControlEx grid = DesignRuleGrid; if (grid != null && grid.GridView != null) { grid.GridView.SetRowCellValue(e.RowHandle, e.Column, e.Value); } } } private void OnDesignRuleCellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e) { if (this._loadingDesignRuleGrid || !IsDesignMode()) return; if (this._currentSchemeNode == null) return; this._currentSchemeDirty = true; UpdateSchemeStatus(); } private DataTable LoadFieldConfigTable(string moduleCode, bool showMessage) { this._fieldConfigTable = new DataTable(); if (string.IsNullOrWhiteSpace(moduleCode)) { this.lblDesignerStatus.Text = "未获取到 ModuleCode,无法加载字段配置"; return this._fieldConfigTable; } try { DataTable gridColumns = BaseModuleImpl.GetBaseGridColumns(moduleCode); this._fieldConfigTable = gridColumns == null ? new DataTable() : gridColumns.Copy(); } catch (Exception ex) { if (showMessage) { MessageUtil.Show("字段配置加载失败:" + ex.Message); } } return this._fieldConfigTable; } private string GetCurrentModuleCode() { TreeNodeData currentData = this._currentSchemeNode == null ? null : this._currentSchemeNode.Tag as TreeNodeData; if (currentData != null) { if (IsDesignMode() && this.chkBindModule.Checked) { string selectedBindModuleCode = GetSelectedBindModuleCode(); if (!string.IsNullOrWhiteSpace(selectedBindModuleCode)) return selectedBindModuleCode; } if (currentData.BindModule && !string.IsNullOrWhiteSpace(currentData.BindModuleCode)) { return currentData.BindModuleCode; } if (currentData.MenuRow != null) { string purviewId = GetRowValue(currentData.MenuRow, "PurviewId"); if (!string.IsNullOrWhiteSpace(purviewId)) return purviewId; } } if (this.Model != null && !string.IsNullOrWhiteSpace(this.Model.ModuleCode)) { return this.Model.ModuleCode; } return string.Empty; } private string FindColumnName(DataTable table, params string[] candidates) { if (table == null || candidates == null) return string.Empty; foreach (string candidate in candidates) { foreach (DataColumn column in table.Columns) { if (string.Equals(column.ColumnName, candidate, StringComparison.OrdinalIgnoreCase)) { return column.ColumnName; } } } return string.Empty; } private string GetSourceValue(DataRow row, string columnName) { if (row == null || string.IsNullOrWhiteSpace(columnName) || !row.Table.Columns.Contains(columnName)) return string.Empty; return row[columnName] + ""; } private int ToPositiveInt(object value, int defaultValue) { int result; return int.TryParse(value + "", out result) && result > 0 ? result : defaultValue; } private int GetFieldTypeId(DataRow row) { if (row == null || row.Table == null) return 0; foreach (string columnName in GetFieldTypeIdColumnCandidates()) { string actualColumnName = FindColumnName(row.Table, columnName); if (string.IsNullOrWhiteSpace(actualColumnName)) continue; int fieldTypeId = ToPositiveInt(GetSourceValue(row, actualColumnName), 0); if (fieldTypeId > 0) return fieldTypeId; } return 0; } private string[] GetFieldTypeIdColumnCandidates() { return new string[] { "fieldTypeId", "FieldTypeId", "fieldtypeid", "fieldSqlTag", "fieldsqlTag", "fieldsqltag", "FieldSqlTag", "ControlType", "controlType", "FieldType", "fieldType", "typeid", "TypeId" }; } private string GetViewUserName(DataRow sourceRow, DataRow schemeRow) { string userName = GetSourceValue(sourceRow, FindColumnName(sourceRow == null ? null : sourceRow.Table, "username", "username1", "UserName", "sysname", "SysName", "controlLabel", "ControlLabel")); if (!string.IsNullOrWhiteSpace(userName)) return userName; return GetSourceValue(schemeRow, "UserName"); } private FieldDesignItem CreateFieldDesignItem(DataRow row) { return CreateFieldDesignItem(row, null); } private FieldDesignItem CreateFieldDesignItem(DataRow fieldRow, DataRow schemeControlRow) { string fieldName = GetSourceValue(fieldRow, "FieldName"); if (string.IsNullOrWhiteSpace(fieldName)) { fieldName = GetSourceValue(schemeControlRow, "FieldName"); } if (string.IsNullOrWhiteSpace(fieldName)) return null; DataRow configRow = GetMatchedFieldConfigRow(this._fieldConfigTable, fieldName); string userName = GetSourceValue(fieldRow, "UserName"); if (string.IsNullOrWhiteSpace(userName)) { userName = GetViewUserName(configRow, schemeControlRow); } if (string.IsNullOrWhiteSpace(userName)) { userName = GetSourceValue(schemeControlRow, "UserName"); } if (string.IsNullOrWhiteSpace(userName)) { userName = fieldName; } int fieldTypeId = GetFieldTypeId(configRow); return new FieldDesignItem { UserName = userName, FieldName = fieldName, FieldTypeId = fieldTypeId, ControlWidth = ToPositiveInt(GetSourceValue(schemeControlRow, "ControlWidth"), DesignFieldControlWidth), ControlHeight = ToPositiveInt(GetSourceValue(schemeControlRow, "ControlHeight"), DesignFieldControlHeight) }; } private void UpdateSchemeStatus() { TreeNodeData nodeData = this._currentSchemeNode == null ? null : this._currentSchemeNode.Tag as TreeNodeData; string schemeName = nodeData == null ? "当前方案" : nodeData.SchemeName; int count = GetNumberRuleGridRowCount(); this.lblDesignerStatus.Text = string.Format("{0},已设置 {1} 条规则", schemeName, count); } private int GetNumberRuleGridRowCount() { GridControlEx grid = DesignRuleGrid; if (grid == null || grid.GridView == null) return 0; return grid.GridView.DataRowCount; } } }