using DevExpress.XtraGrid.Columns; using DevExpress.XtraGrid.Views.Grid; using DevExpress.XtraTreeList.Columns; using Lskj.Business; using Lskj.Business.Impl; using Lskj.Control; using Lskj.Control.Model; using Lskj.Data; using Lskj.Model; using Lskj.Util; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace Lskj.PubBomImport { public partial class FrmBillInfo : UserControl { public DynamicBomImport Model; public DynamicBillModel SysModel; public BillModel billModel; public MyControl ControlObj; public event EventHandler OnControlSourceBind; /// /// 单据明细列 /// private DataTable _detailColumns; private string guidField = "xxxxx_guid"; public GridView GcMainView { get { return gcMain.GridView; } } public FrmBillInfo() { InitializeComponent(); } public void OnLoad(DynamicBomImport mainModel) { Model = mainModel; GetControlData(mainModel); InitControlView(); SetControlData(); } public void GetControlData(DynamicBomImport Model) { string[] args = new[] { Model.FormText, Model.UserId, Model.UserName, Model.Privilege, Model.ModuleCode, "", Model.ModuleCode }; SysModel = new DynamicBillModel(args); SysModel.BillMasterSql = Model.BillMasterSql; SysModel.BillDetailSql = ""; DataRow modelRow = BillImpl.GetBillInfo(SysModel.ModuleCode);//获取单个模块信息 billModel = new BillModel(modelRow);//初始化类的新实例。 if (billModel != null) { billModel.TypeName = string.IsNullOrEmpty(SysModel.BillMasterSql) ? SysModel.FormText : billModel.TypeName;// 模块名称 string masterPreFix = BaseImpl.GetColumnPrefix(billModel.MasterTable);// 主表列前缀 billModel.MasterPreFix = masterPreFix; string detailPreFix = BaseImpl.GetColumnPrefix(billModel.DetailTable);// 明细表列前缀 billModel.DetailPreFix = detailPreFix; billModel.DetailOrderField = billModel.DetailPreFix + "lsidx_id";// 单据来源id if (SystemInfo.Instance.IsNotBillDetailOrder)//禁用排序 { billModel.DetailOrderField = string.Empty; } } DataRow menuRow = BaseImpl.GetMenuConfigTab(SysModel.ModuleId);//获取菜单其他配置 if (menuRow != null) { billModel.BillSourceIds = menuRow.Table.Columns.Contains("BillSourceIds") ? (menuRow["BillSourceIds"] + "").Trim(',') : string.Empty; billModel.BillFlag = menuRow.Table.Columns.Contains("BillFlag") && !string.IsNullOrEmpty(menuRow["BillFlag"] + "") ? Convert.ToInt32(menuRow["BillFlag"] + "") : -1; } DataTable controls = BaseModuleImpl.GetControlLocation(billModel.FormKey, SysModel.ModuleCode); DataTable groups = BaseModuleImpl.GetAddGroupData(billModel.FormKey);//获取主信息分组数据 ControlObj = new MyControl() { Model = SysModel };//主表控件 ControlObj.OtherParams = SysModel.OtherParams(); ControlObj.OnDataSourceBindCallBack += (s, e) => { if (OnControlSourceBind != null) { OnControlSourceBind(null, null); } }; ControlObj.InitControl(controls, this.pl_main_center_master, groups); if (SysModel.GridEnumObj == GridEnum.BandedGridView || billModel.AutoMultiHeader == 1) { this.pl_main_center_detail.Controls.Clear(); this.gcMain = new BandedGridControlEx(); this.gcMain.Model = SysModel; this.gcMain.Dock = DockStyle.Fill; this.pl_main_center_detail.Controls.Add(this.gcMain); } _detailColumns = BillImpl.GetDetailColumns(SysModel.ModuleCode);//初始化单据明细列 if (SysModel.GridEnumObj == GridEnum.BandedGridView || billModel.AutoMultiHeader == 1) { //多表头sql要增加一个判断,否则多表头会出错 _detailColumns = BillImpl.GetDetailColumns(SysModel.ModuleCode, true);//初始化单据明细列 } this.gcMain.DisableFieldSources = billModel.DisableFieldSources; this.gcMain.Model = SysModel; this.gcMain.ParentControl = ControlObj;//把主表控件赋给 单据主表控件、基础档案查询条件控件等等 this.gcMain.SetEditColumns(_detailColumns, GridCustomColumnStruct.BillDetailGridView + billModel.FormKey);//设置可编辑列 } public void InitControlView() { } public void SetControlData() { } public void InitializeHeader(DataRow parentRow, string controlSql) { // 新增 if (!string.IsNullOrEmpty(controlSql)) { string billMasterSql = controlSql; billMasterSql = ReplaceHelper.ReplaceRowParam(parentRow, billMasterSql); // 处理单据表头数据 DataRow row = BillImpl.GetDataRowResult(billMasterSql); if (row != null) { ControlObj.SetAllControlValue(row, true); } } } public bool BillSave(int comfirm = 0, bool canTipMsg = true) { bool saveResult = false; if (ControlObj.VerifyNull()) { // 保存之前先进行表格更新 if (billModel.DetailTreeTable) { (this.gcMain as TreeGridControlEx).TreeListObj.PostEditor(); } else { this.gcMain.GridView.PostEditor(); this.gcMain.GridView.UpdateCurrentRow(); } try { if (this.gcMain.VerifyNull()) { if (this.gcMain.RepeatedVerificationNames.Count > 0 && this.gcMain.VerifyDuplicateColumns()) { //MessageUtil.Show("表格中数据内容重复,保存失败!"); return saveResult; } string billNo = this.lblOrderNo.Text.Trim(); string detailGuid = Guid.NewGuid().ToString(); string masterSql = GetAddRecord(ref billNo); string detailSql = GetDetailRecord(detailGuid, billNo).ToString(); // 检查单据头数据合法性 if (string.IsNullOrEmpty(masterSql)) return false; // 验证明细合法性 if (string.IsNullOrEmpty(detailSql) && !billModel.SaveNullDetail) { MessageUtil.Show(ResourceKeys.BillDetailIsNotNull); return false; } string tipMsg = string.Empty; int result = BillImpl.BillSave(masterSql, detailSql, billModel.DetailTable, ref billNo, detailGuid, billModel.BillSeq, billModel.SaveState ? 2 : 1, comfirm, out tipMsg, 0, billModel.NewVer); if (result == 1) { saveResult = true; } else { throw new Exception($"保存Bom失败\r\n{tipMsg}"); } } } catch (Exception ex) { throw new Exception($"保存Bom失败\r\n{ex.Message}"); } } return saveResult; } private string GetAddRecord(ref string parmaryValue) { if (billModel.NewVer == 0) { // 检查当前的单据号是否已被占用. string newBillNo = BillImpl.GetBillNo(billModel.BillSeq); if (!parmaryValue.Equals(newBillNo)) { if (MessageUtil.Show(ResourceKeys.BillRecordRepeat, MessageBoxButtons.YesNo) == DialogResult.No) { return string.Empty; } else { this.lblOrderNo.Text = newBillNo; parmaryValue = newBillNo; } } } StringBuilder fieldBuilder = new StringBuilder(); StringBuilder valueBuilder = new StringBuilder(); DataTable DetailedProperties = BaseImpl.GetDataTableResult(string.Format("select COLUMN_NAME,DATA_TYPE,CHARACTER_MAXIMUM_LENGTH from information_schema.columns where table_name = '{0}'", billModel.MasterTable)); string errorMessage = string.Empty;//数据不符合数据库规范的信息 foreach (ControlModel model in this.ControlObj.ControlModels) { if (!model.IsSave || model.FieldName.Equals(billModel.PrimaryKey, StringComparison.OrdinalIgnoreCase) || model.FieldName.Equals(billModel.RtagidKey, StringComparison.OrdinalIgnoreCase) || model.FieldType == ControlType.LabPic || model.FieldType == ControlType.LabPicEx) continue; string fieldValue = this.ControlObj.GetControlValue(model); if (SystemInfo.Instance.TrimWhiteSpace) fieldValue = fieldValue.Trim(); if (fieldValue == "****") continue; errorMessage = errorMessage + DatabaseFormatJudgment.SaveOrModifyBalidation(DetailedProperties, model, fieldValue); if (string.IsNullOrEmpty(fieldValue) && model.Isintordecimal) fieldValue = "0";//数值保存时为空的话默认保存为0; fieldBuilder.Append(model.FieldName + ","); valueBuilder.Append(string.IsNullOrEmpty(fieldValue) ? this.ControlObj.GetNullValue(model) : string.Format("N'{0}',", fieldValue)); } // 增加主键 fieldBuilder.Append(billModel.PrimaryKey); valueBuilder.Append("N'" + parmaryValue + "'"); // 增加红蓝字单标记 fieldBuilder.Append("," + billModel.RtagidKey); valueBuilder.Append(",N'" + (rdRed.Checked ? 1 : 0) + "'"); return string.Format("insert into {0}({1}) values ({2})", billModel.MasterTable, fieldBuilder.ToString().TrimEnd(','), valueBuilder.ToString().TrimEnd(',')); } private StringBuilder GetDetailRecord(string guid, string billNo) { // 构造明细 StringBuilder detailBuilder = new StringBuilder(); DataTable detailTable = this.gcMain.GridControl.DataSourceTable().TrimDeleteRows(); if (billModel.DetailTreeTable) { detailTable = ((this.gcMain as TreeGridControlEx).TreeListObj.DataSource as DataTable).TrimDeleteRows(); } DataTable DetailedProperties = BaseImpl.GetDataTableResult(string.Format("select COLUMN_NAME,DATA_TYPE,CHARACTER_MAXIMUM_LENGTH from information_schema.columns where table_name = '{0}'", billModel.DetailTable + "_temp"));//单据明细性表 if (detailTable.Rows.Count > 0) { int lineNumber = 1; DataTable BillColumns = BaseImpl.GetDataTableResult(string.Format("select * from {0} where 1<>1", billModel.DetailTable)); DataTable BillTempColumns = BaseImpl.GetDataTableResult(string.Format("select * from {0} where 1<>1", billModel.DetailTable + "_temp")); foreach (DataRow dataRow in detailTable.Rows) { string errorMessage = string.Empty;//数据不符合数据库规范的信息 StringBuilder fields = new StringBuilder(); StringBuilder values = new StringBuilder(); string detailSql = @"insert into " + billModel.DetailTable + "_temp" + "({0}) values({1})"; fields.Append("sysstr,"); values.Append("'" + guid + "',"); foreach (DataColumn item in BillColumns.Columns) { if (item.ColumnName.Equals(guidField) || item.ColumnName.Equals(ERPInfo.Instance.isAddRows)) continue; if (!BillTempColumns.Columns.Contains(item.ColumnName)) { string type = "varchar(100)"; if (item.DataType == typeof(DateTime)) { type = "datetime"; } BaseImpl.ExecSqlValue(string.Format("alter table {0} add {1} {2}", billModel.DetailTable + "_temp", item.ColumnName, type)); } if (billModel.DetailTreeTable) { TreeListColumn[] TreeListColumns = (this.gcMain as TreeGridControlEx).TreeListObj.Columns.Cast().Where(x => x.FieldName.Equals(item.Caption, StringComparison.OrdinalIgnoreCase)).ToArray(); if (TreeListColumns.Count() == 0 && item.Caption.Equals(billModel.PrimaryDetailKey)) { string primaryValues = dataRow[billModel.PrimaryDetailKey] + ""; if (!string.IsNullOrWhiteSpace(primaryValues)) { fields.Append(item.ColumnName + ","); values.Append("N'" + primaryValues.Replace("'", "''") + "',"); } } if (TreeListColumns.Count() == 0) continue; } else { GridColumn[] gridColumns = gcMain.GridView.Columns.Cast().Where(x => x.FieldName.Equals(item.Caption, StringComparison.OrdinalIgnoreCase)).ToArray(); if (gridColumns.Count() == 0 && item.Caption.Equals(billModel.PrimaryDetailKey)) { string primaryValues = dataRow[billModel.PrimaryDetailKey] + ""; if (!string.IsNullOrWhiteSpace(primaryValues)) { fields.Append(item.ColumnName + ","); values.Append("N'" + primaryValues.Replace("'", "''") + "',"); } } if (gridColumns.Count() == 0) continue; } fields.Append(item.ColumnName + ","); string fieldValue = dataRow.Table.Columns.Contains(item.ColumnName) ? dataRow[item.ColumnName] + "" : string.Empty; //if (SystemInfo.Instance.TrimWhiteSpace) // fieldValue = fieldValue.Trim(); if (item.ColumnName.Equals(billModel.PrimaryDetailKey, StringComparison.OrdinalIgnoreCase)) fieldValue = billNo; if (!string.IsNullOrWhiteSpace(fieldValue)) { values.Append(item.DataType == typeof(DateTime) ? "'" + Convert.ToDateTime(fieldValue).ToString("yyyy-MM-dd HH:mm:ss") + "'," : fieldValue.Contains("'") ? "N'" + fieldValue.Replace("'", "''") + "'," : "N'" + fieldValue + "',"); } else { if (item.DataType == typeof(Decimal) || item.DataType == typeof(Double) || item.DataType == typeof(Int16) || item.DataType == typeof(Int32) || item.DataType == typeof(Int64)) values.Append("0,"); else if (item.DataType == typeof(DateTime)) { values.Append("NULL,"); } else { values.Append("'',"); } } errorMessage = errorMessage + DatabaseFormatJudgment.SaveOrModifyBalidation(_detailColumns, DetailedProperties, dataRow, item, fieldValue); } detailBuilder.AppendFormat(detailSql, fields.ToString().Trim(','), values.ToString().Trim(',')); if (!string.IsNullOrWhiteSpace(errorMessage)) errorMessage = "第" + lineNumber + "行:" + errorMessage; lineNumber++; } } return detailBuilder; } private void SetBillStatus(DataRow rowItem) { // 单据为新增状态 this.dbpFP.Enabled = this.btnDelete.Enabled = this.btnBillSave.Enabled = this.btnBillApply.Enabled = true; this.lbTitle.Text = billModel.TypeName + "(新增)"; this.lblOrderNo.Text = BillImpl.GetBillNo(billModel.BillSeq); this.cb_input.Enabled = this.btn_input.Enabled = this.txt_input.Enabled = true; this.cb_templete.Enabled = true; this.billModel.SaveState = false; this.ControlObj.SetReadOnlyAllControl(false); this.rdBlue.Enabled = this.rdRed.Enabled = true; // 通过右键菜单打开单据,假如明细有数据则在初始化时使用传入数据.