using Lskj.Business; using Lskj.Business.Impl; using Lskj.Control; using Lskj.Control.BrowserSetting; using Lskj.Control.Model; using Lskj.Core; using Lskj.Model; using Lskj.Util; using Microsoft.WindowsAPICodePack.Shell; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Net; using System.Windows.Forms; namespace Lskj.PubArtworkDynamic.Control { public partial class ModuleGrid : UserControl { /// /// 模块类 /// public ViewModel MainViewModel; /// /// 表格控件 /// public GridControlEx MainGridEx { get { return gc_Main; } } /// /// 明细Model /// public GridDetailModel DetailModel; /// /// 条件控件 /// public MyControl SearchMainObj; /// /// 左侧节点上方主键 /// private string leftTopGridIdValue { get { ModuleGridDetail moduleGridDetail = (ModuleGridDetail)MainViewModel.LeftTabControl.TabControlObj.SelectedTabPage.Controls[0]; string rtnString = ""; DataRow dataRow = moduleGridDetail.TopGridEx.GridView.GetFocusedDataRow(); if (dataRow != null) { if (!string.IsNullOrEmpty(MainViewModel.MoudleMainObj.UploadIdValueField) && dataRow.Table.Columns.Contains(MainViewModel.MoudleMainObj.UploadIdValueField)) { rtnString = dataRow[MainViewModel.MoudleMainObj.UploadIdValueField] + ""; } } return rtnString; } } /// /// 左侧节点上方主键 /// private string leftBottomGridIdValue { get { ModuleGridDetail moduleGridDetail = (ModuleGridDetail)MainViewModel.LeftTabControl.TabControlObj.SelectedTabPage.Controls[0]; string rtnString = ""; DataRow dataRow = moduleGridDetail.BottomGridEx.GridView.GetFocusedDataRow(); if (dataRow != null) { if (!string.IsNullOrEmpty(MainViewModel.MoudleMainObj.UploadIdValueField) && dataRow.Table.Columns.Contains(MainViewModel.MoudleMainObj.UploadIdValueField)) { rtnString = dataRow[MainViewModel.MoudleMainObj.UploadIdValueField] + ""; } } return rtnString; } } /// /// 文件大小 /// private static readonly string[] suffixes = new string[] { " B", " KB", " MB", " GB", " TB", " PB" }; /// /// 构造函数 /// /// public ModuleGrid(GridDetailModel model) { DetailModel = model; InitializeComponent(); Load += OnModuleGridDetailLoad; btnAdd.Click += OnBtnAddClick; btnDel.Click += OnBtnDelClick; } /// /// 加载完成后 /// /// /// private void OnModuleGridDetailLoad(object sender, EventArgs e) { try { gc_Main.GridView.OptionsSelection.MultiSelectMode = DevExpress.XtraGrid.Views.Grid.GridMultiSelectMode.RowSelect; gc_Main.Tag = DetailModel; if (DetailModel.IsReadOnly) { this.SearchMainObj = new MyControl(DetailModel.DetailSql, gc_Main);//构建主表mycontrol } else { this.SearchMainObj = new MyControl(DetailModel.SystemModel.MenuSql, gc_Main);//构建主表mycontrol } DataTable gridColumns = new DataTable(); if (!string.IsNullOrEmpty(DetailModel.UnionModule)) { gridColumns = BaseModuleImpl.GetBaseGridColumns(DetailModel.UnionModule); } else { gridColumns = ReportImpl.GetReportDetailColumns(MainViewModel.SysModel.ModuleCode, DetailModel.Id + ""); } gc_Main.GridView.OptionsBehavior.Editable = false; gc_Main.SetReadOnlyColumns(gridColumns, GridCustomColumnStruct.BaseMainGridView + DetailModel.FormKey);//明细 DynamicModel dyncModel = new DynamicModuleModel(new string[] { DetailModel.DetailName, ERPInfo.Instance.UserId, ERPInfo.Instance.UserName, MainViewModel.SysModel.Privilege, DetailModel.UnionModule, "0" }); if (!string.IsNullOrEmpty(DetailModel.SystemModel.ModeCode)) { gc_Main.SetGridRightMenus(BaseModuleImpl.GetBaseGridRightMenus(DetailModel.SystemModel.ModeCode), dyncModel, OnRightMenuCallBack, this.SearchMainObj); } else if (!string.IsNullOrEmpty(DetailModel.FormKey)) { gc_Main.SetGridRightMenus(BaseModuleImpl.GetBaseGridRightMenus(DetailModel.FormKey), dyncModel, OnRightMenuCallBack, this.SearchMainObj); } } catch (Exception ex) { MessageUtil.Show(ex.Message); } } /// /// 上传按钮点击事件 /// /// /// private void OnBtnAddClick(object sender, EventArgs e) { try { string resultStr = string.Empty; OpenFileDialog dialog = new OpenFileDialog(); dialog.Multiselect = true;//该值确定是否可以选择多个文件 dialog.Title = "请选择文件"; string filter = SqlHelper.ExecuteScalar(@"select 合并字段=stuff((select '|'+Mix_apellation+'(*'+bases1 +')'+'|*'+bases1 from P_BaseMixInfoTab b where Tag=a.Tag for xml path('')),1,1,'') from P_BaseMixInfoTab a where Tag='70700201' group by Tag ") + ""; dialog.Filter = string.IsNullOrWhiteSpace(filter) ? "所有文件(*.*)|*.*" : filter; if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) { WaitForm.ShowForm("文件上传中..."); foreach (string fileName in dialog.FileNames) { string outMsg = ""; bool isUpload = false; if (filter.ToLower().Contains(Path.GetExtension(fileName).ToLower())) { isUpload = UploadFile(fileName, out outMsg); } else { outMsg = "该文件类型不允许上传"; } if (!isUpload) { resultStr += string.Format("文件{0}上传失败,原因:{1}\r\n", Path.GetFileName(fileName), outMsg); } } if (!string.IsNullOrEmpty(resultStr)) { MessageUtil.Show(resultStr); } WaitForm.HideForm(); } } catch (Exception) { } finally { RefushWaitDetail(); } } /// /// 删除操作页签附件数据 /// /// /// private void OnBtnDelClick(object sender, EventArgs e) { try { DataTable dataTable = gc_Main.gridControl.DataSource as DataTable; int[] rowNumbers = gc_Main.GridView.GetSelectedRows(); string resultStr = string.Empty; foreach (int rowIndex in rowNumbers) { DataRow rowItem = gc_Main.GridView.GetDataRow(rowIndex); bool isDelete = false; isDelete = DeleteFile(rowIndex); if (!isDelete) { gc_Main.GridView.UnselectRow(rowIndex); resultStr += string.Format("文件{0}删除失败\r\n", rowItem["name"]); } } if (!string.IsNullOrEmpty(resultStr)) { MessageUtil.Show(resultStr); } gc_Main.GridView.DeleteSelectedRows(); gc_Main.GridView.SelectRow(dataTable.Rows.Count - 1); gc_Main.GridView.FocusedRowHandle = dataTable.Rows.Count - 1; } catch (Exception) { } finally { RefushWaitDetail(); } } /// /// 刷新等待区 /// public void RefushWaitDetail() { try { if (MainViewModel.LeftTabControl.TabControlObj.SelectedTabPage != null && MainViewModel.RightTabControl.TabControlObj.SelectedTabPage != null) { ModuleGridDetail moduleGridDetail = MainViewModel.LeftTabControl.TabControlObj.SelectedTabPage.Controls[0] as ModuleGridDetail; DataRow rowItem = moduleGridDetail.TopGridEx.GetViewFocusedDataRow(); if (rowItem != null && this.MainGridEx.Tag != null && this.MainGridEx.Tag is GridDetailModel) { GridDetailModel gridDetailModel = this.MainGridEx.Tag as GridDetailModel; string sqlValue = this.GetSearchSql(gridDetailModel, rowItem); DataTable dataTable = MainImpl.GetDataTableResult(sqlValue); this.MainGridEx.SetGridViewDataSource(dataTable); this.MainGridEx.LastSearchSql = sqlValue; } } } catch (Exception ex) { MessageUtil.Show(ex.Message); } } /// /// 获取查询条件 /// /// /// /// private string GetSearchSql(GridDetailModel model, DataRow rowItem) { string fieldName = !string.IsNullOrEmpty(model.UnionParentField) && rowItem.Table.Columns.Contains(model.UnionParentField) ? model.UnionParentField : MainViewModel.MoudleMainObj.ParmaryKey; string sqlValue = model.IsReadOnly || model.IsChart ? model.DetailSql : model.SystemModel.MenuSql; sqlValue = ReplaceHelper.ReplaceRowParam(rowItem, sqlValue); if (ReplaceHelper.IsSelect(sqlValue) && !string.IsNullOrEmpty(model.UnionValue)) { sqlValue = ReplaceHelper.ReplaceWhereCond(sqlValue) + string.Format(" and {0}='{1}'", model.UnionValue, rowItem[fieldName] + ""); } if (!string.IsNullOrEmpty(model.UnionCond)) { string UnionCond = ReplaceHelper.ReplaceRowParam(rowItem, model.UnionCond); sqlValue += UnionCond; } return sqlValue; } /// /// 上传文件 /// /// /// private bool UploadFile(string filePath, out string msg) { bool isUpload = false; string File = filePath; string returnMsg = ""; string postUrl = ""; try { //获取文件信息 System.IO.FileInfo fileInfo = new FileInfo(File); string suffix = Path.GetExtension(File); //获取Excel等文件信息 string fileAuthor = ""; string fileType = ""; try { var file = ShellFile.FromFilePath(File); string[] oldAuthors = file.Properties.System.Author.Value;//作者 if (oldAuthors != null && oldAuthors.Length > 0) { fileAuthor = string.Join(",", oldAuthors); } else { fileAuthor = ""; } fileType = file.Properties.System.ItemTypeText.Value + ""; } catch (Exception) { fileType = Path.GetExtension(File).TrimStart(','); } string name = fileInfo.Name; DateTime creationTime = fileInfo.CreationTime; string fileSize = BytesToReadableValue(fileInfo.Length); byte[] fileBytes = ConvertFileToBytes(File); string fileStream = Convert.ToBase64String(fileBytes); string userId = ERPInfo.Instance.UserId; DateTime uploadTime = DateTime.Now; //上传文件到服务器目录 postUrl = "{0}Api/FileUploadApi.ashx?moduleId={1}&idValue={2}&folder={3}&totsize={4}&position={5}&filename={6}&method={7}"; if (!string.IsNullOrEmpty(leftTopGridIdValue)) { string token = ""; string loginUrl = $"{SystemInfo.Instance.OAUrl}/Api/SysUserAjaxApi.ashx"; HttpTools.setting("application/x-www-form-urlencoded", null, null, HttpTools.Encode.UTF8); Dictionary loginPmsDic = new Dictionary(); loginPmsDic.Add("method", "Login"); loginPmsDic.Add("username", ERPInfo.Instance.UserName); loginPmsDic.Add("password", ERPInfo.Instance.InPassWord); HttpWebResponse loginResponse = HttpTools.Post(loginUrl, "", loginPmsDic, HttpTools.Method.POST, out CookieCollection loginCookie, out string loginResult); if (loginResponse != null && !string.IsNullOrEmpty(loginResult)) { JObject jObject = JsonConvert.DeserializeObject(loginResult); if (jObject.ContainsKey("success")) { if ((jObject["success"] + "").Equals("True")) { if (jObject.ContainsKey("token")) { token = jObject["token"] + ""; } } } } if (!string.IsNullOrEmpty(token)) { postUrl = string.Format(postUrl, SystemInfo.Instance.OAUrl, this.MainViewModel.SysModel.ModuleCode, leftTopGridIdValue, "UploadFilesTemp", fileBytes.Length, 0, name, "DoWebUpload"); HttpTools.setting("application/x-www-form-urlencoded", null, null); string result = ""; CookieCollection cookieCollection = null; Dictionary headerDic = new Dictionary(); headerDic.Add("Authorization", $"Bearer {token}"); HttpWebResponse webResponse = HttpTools.Post(postUrl, fileStream, null, headerDic, HttpTools.Method.POST, out cookieCollection, out result); if (webResponse != null && !string.IsNullOrEmpty(result)) { JObject jsonObject = (JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(result); string isSuccess = jsonObject["success"] + ""; if (isSuccess.Equals("True", StringComparison.CurrentCultureIgnoreCase)) { string fileId = jsonObject["other"] + ""; string webpath = jsonObject["data"]["WebRelPath"] + ""; string searchSql = @"update P_fm_FileTab set author='{2}',CreationTime='{3}' ,Uploader='{4}',UploaderId='{5}' ,UploadTime='{6}' ,Pid='{1}' where dllcoid = '{0}' and fileId='{7}' "; searchSql = string.Format(searchSql, this.MainViewModel.SysModel.ModuleCode, this.leftTopGridIdValue, fileAuthor, fileInfo.CreationTime, ERPInfo.Instance.UserName, ERPInfo.Instance.UserId, uploadTime, fileId); SqlHelper.ExecuteNonQuery(searchSql); isUpload = true; } else { if (jsonObject.ContainsKey("msg")) { returnMsg = jsonObject["msg"] + ""; } isUpload = false; } } else { returnMsg = "上传请求失败"; isUpload = false; } } else { returnMsg = loginResult; isUpload = false; } } else { returnMsg = "上传节点值不能为空"; isUpload = false; } } catch (Exception ex) { returnMsg = ex.Message; isUpload = false; } msg = returnMsg; return isUpload; } /// /// 删除文件 /// /// /// private bool DeleteFile(int rowIndex) { DataRow rowItem = gc_Main.GridView.GetDataRow(rowIndex); bool isDelete = false; try { string token = ""; string loginUrl = $"{SystemInfo.Instance.OAUrl}/Api/SysUserAjaxApi.ashx"; HttpTools.setting("application/x-www-form-urlencoded", null, null, HttpTools.Encode.UTF8); Dictionary loginPmsDic = new Dictionary(); loginPmsDic.Add("method", "Login"); loginPmsDic.Add("username", ERPInfo.Instance.UserName); loginPmsDic.Add("password", ERPInfo.Instance.InPassWord); HttpWebResponse loginResponse = HttpTools.Post(loginUrl, "", loginPmsDic, HttpTools.Method.POST, out CookieCollection loginCookie, out string loginResult); if (loginResponse != null && !string.IsNullOrEmpty(loginResult)) { JObject jObject = JsonConvert.DeserializeObject(loginResult); if (jObject.ContainsKey("success")) { if ((jObject["success"] + "").Equals("True")) { if (jObject.ContainsKey("token")) { token = jObject["token"] + ""; } } } } if (!string.IsNullOrEmpty(token)) { //删除文件 //string postUrl = "{0}Api/FileUploadApi.ashx?moduleId={1}&idValue={2}&folder={3}&filename={4}&method={5}"; string postUrl = "{0}Api/FileUploadApi.ashx?fileId={1}&filename={2}&method={3}"; //postUrl = string.Format(postUrl, SystemInfo.Instance.OAUrl, this.Model.ModuleCode, "", "UploadFilesTemp", rowItem["name"], "DoDelete"); postUrl = string.Format(postUrl, SystemInfo.Instance.OAUrl, rowItem["fileId"], rowItem["webpath"], "DoDelete"); HttpTools.setting("application/x-www-form-urlencoded", null, null); string result = ""; CookieCollection cookieCollection = null; HttpWebResponse webResponse = HttpTools.Post(postUrl, "", null, HttpTools.Method.POST, out cookieCollection, out result); if (webResponse != null && !string.IsNullOrEmpty(result)) { JObject jsonObject = (JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(result); string isSuccess = jsonObject["success"] + ""; if (isSuccess.Equals("True", StringComparison.CurrentCultureIgnoreCase)) { isDelete = true; } else { isDelete = false; } } else { isDelete = false; } } else { isDelete = false; } } catch (Exception) { isDelete = false; } return isDelete; } /// /// 获取文件大小的显示字符串 /// /// /// public static string BytesToReadableValue(double number) { double last = 1; for (int i = 0; i < suffixes.Length; i++) { var current = Math.Pow(1024, i + 1); var temp = number / current; if (temp < 1) { return (number / last).ToString("n2") + suffixes[i]; } last = current; } return number.ToString(); } /// /// 附件转换byte[] /// /// 附件路径 /// 二进制