using System.Collections;
using System.Data;
using System.Data.SqlClient;
using System.Dynamic;
using Gs.Toolbox;
using Gs.Toolbox.ApiCore.Abstract.Mvc;
using Gs.Toolbox.ApiCore.Common.Mvc;
using Gs.Toolbox.ApiCore.Group;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using static Gs.Toolbox.UtilityHelper;
namespace Gs.Sys.Services
{
[ApiGroup(ApiGroupNames.FM)]
public class FmController : IRomteService
{
private readonly IHttpContextAccessor _http;
private readonly string _userCode, _userGuid, _orgFids;
public FmController(IHttpContextAccessor httpContextAccessor)
{
_http = httpContextAccessor;
(_userCode, _userGuid, _orgFids) =
GetUserGuidAndOrgGuid(_http);
}
#region 布局配置
///
/// 保存或清空表单布局
///
///
///
/// Saves layouts: intType 1=standard save, 2=personal save, 3=clear standard, 4=clear personal.
[RequestMethod(RequestMethods.POST)]
public ReturnDto EditModel([FromBody] dynamic model)
{
string applyUserGuid = "";
string formPath = model.formPath;
int intType = model.intType;
// intType: 1 = save standard layout, 2 = save personal layout, 3 = clear standard layout, 4 = clear personal layout.
dynamic m = new ExpandoObject();
m.outMsg = "";
// Gather batched SQL statements so they can be executed transactionally when saving layouts.
Hashtable SQLStringList = new Hashtable();
string _groupGuid = Guid.NewGuid().ToString();
//只有超级管理员权限
if (intType == 1 || intType == 3)
{
// Validate the current user has administrator rights when touching standard layouts.
int? isAdmin = 0;
try
{
isAdmin = chkAdmin();
if (isAdmin <= 0)
{
m.outMsg = "你不是管理员,操作失败!";
return ReturnDto.QuickReturn(m,
ReturnCode.Default, "操作成功!");
}
}
catch (Exception ex)
{
Gs.Toolbox.LogHelper.Debug(this.ToString(),
"EditModel isAdmin error:" + ex.Message);
}
}
//保存标准版
if (intType == 1)
{
// Persist a new standard layout definition shared by all users.
applyUserGuid = null;
Gs.Toolbox.DbHelperSQL.ExecuteSql(
"delete from [FM_LAYOUT] where groupGuid<>'" + _groupGuid +
"' and [formPath]=@formPath and applyUserGuid is null",
new SqlParameter[]
{ new SqlParameter("@formPath", formPath) });
// SQLStringList.Add("delete from [FM_LAYOUT] where groupGuid<>'" + _groupGuid + "' and [formPath]=@formPath and applyUserGuid is null", new SqlParameter[] { new SqlParameter("@formPath", formPath) });
}
//保存个人版本
if (intType == 2)
{
// Persist the caller's personal layout copy scoped to their user GUID.
applyUserGuid = _userGuid;
Gs.Toolbox.DbHelperSQL.ExecuteSql(
"delete from [FM_LAYOUT] where groupGuid<>'" + _groupGuid +
"' and [formPath]=@formPath and applyUserGuid =@applyUserGuid",
new SqlParameter[]
{
new SqlParameter("@formPath", formPath),
new SqlParameter("@applyUserGuid", applyUserGuid)
});
//SQLStringList.Add("delete from [FM_LAYOUT] where groupGuid<>'" + _groupGuid + "' and [formPath]=@formPath and applyUserGuid =@applyUserGuid", new SqlParameter[] { new SqlParameter("@formPath", formPath), new SqlParameter("@applyUserGuid", applyUserGuid) });
}
//清空标准版本
if (intType == 3)
{
// Administrators can wipe the shared standard layout entirely.
applyUserGuid = null;
SQLStringList.Add(
"delete from [FM_LAYOUT] where [formPath]=@formPath and applyUserGuid is null",
new SqlParameter[]
{ new SqlParameter("@formPath", formPath) });
Gs.Toolbox.DbHelperSQL.ExecuteSqlTranRtn(SQLStringList);
m.outMsg = "清空标准版配置成功!";
return ReturnDto.QuickReturn(m, ReturnCode.Success,
"操作成功!");
}
//清空个人版本
if (intType == 4)
{
// Remove the caller's personal layout while keeping the shared standard version intact.
applyUserGuid = _userGuid;
SQLStringList.Add(
"delete from [FM_LAYOUT] where [formPath]=@formPath and applyUserGuid =@applyUserGuid",
new SqlParameter[]
{
new SqlParameter("@formPath", formPath),
new SqlParameter("@applyUserGuid", applyUserGuid)
});
Gs.Toolbox.DbHelperSQL.ExecuteSqlTranRtn(SQLStringList);
m.outMsg = "清空个人版配置成功!";
return ReturnDto.QuickReturn(m, ReturnCode.Success,
"操作成功!");
}
//这是所有的gridview,lay xml
JArray jArray = model.xmlList;
try
{
foreach (var jsonitem in jArray)
{
JObject job = (JObject)jsonitem;
if (job["idName"] != null)
{
// Compose an insert statement for each UI control (grid, layout panel, splitter, etc.).
string idName = job["idName"].ToString();
string idXml = job["idXml"].ToString();
string idType = job["idType"].ToString();
string _splitterPosition =
job["splitterPosition"].ToString();
string splitterPosition =
string.IsNullOrEmpty(_splitterPosition)
? "0"
: _splitterPosition;
System.Text.StringBuilder _sql =
new System.Text.StringBuilder();
_sql.Append(
" INSERT INTO [dbo].[FM_LAYOUT] ([guid] ,[applyUserGuid] ,[formPath] ,[controlId],[controlHeight],[lastUpdateBy],[lastUpdateDate],controlXml,controlType,groupGuid,splitterPosition)");
_sql.Append(
"values(newid(),@applyUserGuid,@formPath,@controlId,@controlHeight,@lastUpdateBy,getdate(),@controlXml,'" +
idType + "','" + _groupGuid + "'," +
splitterPosition + ")");
SQLStringList.Add(_sql, new SqlParameter[]
{
new SqlParameter("@formPath", formPath),
new SqlParameter("@controlId", idName),
new SqlParameter("@controlHeight", "0"),
new SqlParameter("@lastUpdateBy", _userCode),
new SqlParameter("@applyUserGuid", applyUserGuid),
new SqlParameter("@controlXml", idXml)
});
}
}
Gs.Toolbox.DbHelperSQL.ExecuteSqlTranRtn(SQLStringList);
m.outMsg = "保存" + (intType == 1 ? "标准版" : "个人版") + "配置成功!";
return ReturnDto.QuickReturn(m, ReturnCode.Success,
"操作成功!");
}
catch (Exception ex)
{
// 捕获保存查询配置时的异常,并将信息返回给前端。
m.outMsg = "操作失败:" + ex.Message;
Gs.Toolbox.LogHelper.Debug(this.ToString(),
"EditModel error:" + ex.Message);
}
//这是所有的
return ReturnDto.QuickReturn(m, ReturnCode.Default,
"操作成功!");
}
///
/// 读取
///
///
///
/// Combines the shared layout (list) with the current user's override (list2).
[RequestMethod(RequestMethods.POST)]
public ReturnDto GetModel([FromBody] dynamic model)
{
string formPath = model.formPath.ToString();
dynamic m = new ExpandoObject();
m.list = new List();
m.list2 = new List();
SqlParameter[] parameters =
{
new("@formPath", formPath),
new("@userGuid", _userGuid),
};
var dset = new DataSet();
try
{
// Stored procedure returns both standard layout data and any personal override for the current user.
dset = DbHelperSQL.RunProcedure("[fm_get_layout]", parameters,
"0");
if (dset != null && dset.Tables.Count > 0
)
{
// Table[0] represents the standard definition; table[1] holds the user's personal layout snapshot.
var _tb = dset.Tables[0].TableToDynamicList();
m.list = _tb;
var _tb2 = dset.Tables[1].TableToDynamicList();
m.list2 = _tb2;
}
}
catch (Exception ex)
{
// Log retrieval failure but continue returning default result to caller.
LogHelper.Debug(ToString(), ex.Message);
}
if (m != null)
return ReturnDto.QuickReturn(m, ReturnCode.Success,
"读取成功!");
return ReturnDto.QuickReturn(m, ReturnCode.Default,
"读取失败!");
}
///
/// 读取
///
///
///
/// Retrieves the serialized layout string for the latest saved version (standard or personal).
[RequestMethod(RequestMethods.POST)]
public ReturnDto GetModelByVersion([FromBody] dynamic model)
{
string formPath = model.formPath.ToString();
string strMsg = "";
SqlParameter[] parameters =
{
new("@formPath", formPath),
new("@userGuid", _userGuid),
};
var dset = new DataSet();
try
{
// Stored procedure exposes the latest serialized layout snapshot based on formPath and user scope.
dset = DbHelperSQL.RunProcedure("[fm_get_layout_ver]",
parameters, "0");
if (dset != null && dset.Tables.Count > 0
)
{
strMsg = dset.Tables[0].Rows[0][0].ToString();
}
}
catch (Exception ex)
{
// Capture context when reading layout versions fails to help diagnose environment-specific issues.
LogHelper.Debug(ToString(),
ex.Message + ",formPath:" + formPath + ",_userGuid:" +
_userGuid);
}
return ReturnDto.QuickReturn(strMsg, ReturnCode.Success,
"读取成功!");
}
#endregion
private int? chkAdmin()
{
int? isAdmin = 0;
System.Text.StringBuilder _sb = new System.Text.StringBuilder();
// Uses SYS_USER.IS_SYS flag to decide if the caller has elevated privileges.
_sb.Append("select count(1) from [dbo].[SYS_USER] where GUID='" +
_userGuid + "' and IS_SYS=1");
object _obj = Gs.Toolbox.DbHelperSQL.GetSingle(_sb.ToString());
if (_obj == null)
{
isAdmin = 0;
}
else
isAdmin = Gs.Toolbox.UtilityHelper.ToInt(_obj.ToString());
return isAdmin;
}
#region 发送erp新版本
///
///
///
/// keyType:1审核,0反审核
///
/// Packages MES data into ERP payloads and posts them according to the requested operation.
[RequestMethod(RequestMethods.POST)]
public string SendErp([FromBody] dynamic model)
{
//string keyGuid = model.keyGuid; 原生主键
//string keyUserGuid = model.keyUserGuid;操作用户
//string keyProduce = model.keyProduce;存储过程名
//string keyTaskName = model.keyTaskName;任务名
//string keyChild = model.keyChild;任务子节点名
//string keyMeth = model.keyMeth;方法名
//string keyNo = model.keyNo;单据编号
//string keyUrl = model.keyUrl;接口地址
int _rtnInt = 0;
string _rtnStr = "";
try
{
string _erpJson = GetErpParam(model);
if (_erpJson.Length <= 0)
return "-1读取erp参数失败!";
string keyUserGuid = model.keyUserGuid;
string keyGuid = model.keyGuid;
string keyNo = model.keyNo;
string idtype = model.idtype; //这个仅仅是更新工单状态的时候有
string keyUrl = model.keyUrl;
if (string.IsNullOrEmpty(idtype))
{
// 常规接口:按操作类型推送单条业务数据。
(_rtnInt, _rtnStr) = InterfaceUtil.HttpPostErp(_erpJson,
keyUserGuid, keyGuid, keyNo, 0, keyUrl);
}
else
{
// 带 idtype 的请求用于特殊流程(如关闭、反关闭),ERP 需要额外的状态标记。
(_rtnInt, _rtnStr) = InterfaceUtil.HttpPostErp(_erpJson,
keyUserGuid, keyGuid, keyNo, 2, keyUrl);
}
}
catch (Exception ex)
{
// 记录 ERP 数据转换异常,便于定位存储过程或序列化问题。
Gs.Toolbox.LogHelper.Debug(this.ToString(),
"Fm SendErp:" + ex.Message);
return "发送erp失败:" + ex.Message;
}
if (_rtnInt <= 0)
{
return "发送erp失败:" + _rtnStr;
}
return _rtnStr;
}
///
/// 构建erp参数
///
///
///
private string GetErpParam(dynamic model)
{
string keyGuid = model.keyGuid;
string keyUserGuid = model.keyUserGuid;
string keyProduce = model.keyProduce;
string keyTaskName = model.keyTaskName;
string keyChild = model.keyChild;
string keyMeth = model.keyMeth;
string keyNo = model.keyNo;
string idtype = model.idtype; //这个仅仅是更新工单状态的时候有
if (keyMeth.ToUpper() == "delete".ToUpper())
// 删除操作无需向 ERP 推送数据,只需返回空串。
return "";
try
{
System.Data.DataSet dset = new System.Data.DataSet();
SqlParameter[] parameters =
{
new("@inOrderGuid", keyGuid),
new("@inEdtUserGuid", keyUserGuid),
new("@keyMeth", keyMeth.ToLower()),
};
// 调用业务定义的存储过程,将 MES 数据打包给 ERP。
dset = DbHelperSQL.RunProcedure(keyProduce, parameters, "0");
if (dset == null)
return "";
if (dset.Tables.Count <= 0)
return "";
if (dset.Tables[0].Rows.Count <= 0)
return "";
//这是普通的接口
if (string.IsNullOrEmpty(idtype))
{
// 常规出参:第一张表是主数据,第二张表(若存在)是子表集合。
string _mesGuid = dset.Tables[0].Rows[0][0].ToString();
dynamic _datajson = new ExpandoObject();
if (dset.Tables.Count > 1)
{
// 多表返回时,需要把子表集合挂到 datajson 中。
//这是这是普通的接口里的结案,结构和其它不一样
if (keyMeth.ToLower() == "toclose".ToLower() ||
keyMeth.ToLower() == "closure".ToLower() ||
keyMeth.ToLower() == "unfinish")
{
_datajson = dset.Tables[1].Rows[0].RowToDynamic();
}
else
{
_datajson = dset.Tables[0].Rows[0].RowToDynamic();
List _lst =
dset.Tables[1].TableToDynamicList();
((IDictionary)_datajson)[keyChild] =
_lst;
}
}
// var _obj = new
// {
// mesid = _mesGuid,
// taskname = keyTaskName,
// optype = keyMeth,
// datajson = JsonConvert.SerializeObject(_datajson),
// };
// return JsonConvert.SerializeObject(_obj);
return JsonConvert.SerializeObject(_datajson);
}
//这是订单回传标识
List _datajson22 = new List();
dynamic _ob = new ExpandoObject();
_ob.ENTRY = dset.Tables[0].TableToDynamicList();
_datajson22.Add(_ob);
// var _obj22 = new
// {
// taskname = keyTaskName,
// idtype = idtype,
// datajson = JsonConvert.SerializeObject(_datajson22),
// };
// return JsonConvert.SerializeObject(_obj22);
return JsonConvert.SerializeObject(_datajson22);
}
catch (Exception ex)
{
// 记录 ERP 数据转换异常,便于定位存储过程或序列化问题。
Gs.Toolbox.LogHelper.Debug(this.ToString(), ex.Message);
throw ex;
}
}
#endregion
#region 查询
///
/// 读取
///
///
///
[RequestMethod(RequestMethods.POST)]
public ReturnDto GetQuery([FromBody] dynamic model)
{
dynamic m = new ExpandoObject();
m.list = new List();
m.list2 = new List();
m.list3 = new List();
m.list4 = new List();
var _split = "|";
string formPath = model.formPath.ToString();
System.Text.StringBuilder _sb = new System.Text.StringBuilder();
foreach (var _obj in model.list)
{
var _line =
_obj.colName + _split
+ _obj.colCap + _split
;
if (_sb.Length > 0)
_sb.Append("~");
_sb.Append(_line);
}
;
var lst = new List();
// 将列名和显示标题拼成 "~" 分隔的参数,传给存储过程生成查询配置。
SqlParameter[] parameters =
{
new("@formPath", formPath),
new("@colArray", _sb.ToString()),
};
var dset = new DataSet();
try
{
// fm_set_query 会返回查询条件、结果字段、排序等多张配置表。
dset = DbHelperSQL.RunProcedure("[fm_set_query]", parameters,
"0");
if (dset != null && dset.Tables.Count > 0)
{
m.list = dset.Tables[0].TableToDynamicList();
m.list2 = dset.Tables[1].TableToDynamicList();
m.list3 = dset.Tables[2].TableToDynamicList();
m.list4 = dset.Tables[3].TableToDynamicList();
}
}
catch (Exception ex)
{
// 记录 ERP 数据转换异常,便于定位存储过程或序列化问题。
LogHelper.Debug(ToString(), ex.Message);
}
return ReturnDto.QuickReturn(m, ReturnCode.Success,
"读取成功!");
}
///
/// 编辑表
///
///
///
[RequestMethod(RequestMethods.POST)]
public ReturnDto EditQuery([FromBody] dynamic model)
{
dynamic m = new ExpandoObject();
m.outMsg = "";
string formPath = model.formPath;
ArrayList arrayList = new ArrayList();
string _groupGuid = Guid.NewGuid().ToString();
int? isAdmin = 0;
try
{
isAdmin = chkAdmin();
if (isAdmin <= 0)
{
// Query configuration is restricted to administrators to protect shared metadata.
m.outMsg = "你不是管理员,操作失败!";
return ReturnDto.QuickReturn(m, ReturnCode.Default,
"操作成功!");
}
}
catch (Exception ex)
{
// 记录 ERP 数据转换异常,便于定位存储过程或序列化问题。
Gs.Toolbox.LogHelper.Debug(this.ToString(),
"EditModel isAdmin error:" + ex.Message);
}
try
{
// 先清空原有查询来源表,再批量插入最新配置。
Gs.Toolbox.DbHelperSQL.ExecuteSql(
"delete from [FM_QUERY_TABLE] where formPath=@formPath ",
new SqlParameter[]
{ new SqlParameter("@formPath", formPath) });
foreach (var _obj in model.list)
{
System.Text.StringBuilder _sb =
new System.Text.StringBuilder();
_sb.Append(
"INSERT INTO [dbo].[FM_QUERY_TABLE]([guid],[formPath] ,[tableName] ,[lastUpdateBy] ,[lastUpdateDate],[tableOtherName])");
_sb.Append(" values(newid(),'" + formPath + "','" +
_obj.tableName + "','',getdate(),'" +
_obj.tableOtherName + "')");
arrayList.Add(_sb.ToString());
}
Gs.Toolbox.DbHelperSQL.ExecuteSqlTran(arrayList);
}
catch (Exception ex)
{
// 捕获保存查询配置时的异常,并将信息返回给前端。
m.outMsg = ex.Message;
return ReturnDto.QuickReturn(m, ReturnCode.Default,
ex.Message);
}
m.outMsg = "操作成功!";
return ReturnDto.QuickReturn(m, ReturnCode.Default,
"操作成功!");
}
///
/// 删除表
///
///
///
[RequestMethod(RequestMethods.POST)]
public ReturnDto DeleteQuery([FromBody] dynamic model)
{
int? rtnInt = (int)ReturnCode.Default;
int? isAdmin = 0;
try
{
isAdmin = chkAdmin();
if (isAdmin <= 0)
{
// 删除查询配置同样需要管理员权限。
return ReturnDto.QuickReturn(rtnInt,
ReturnCode.Default, "你不是管理员,操作失败!");
}
}
catch (Exception ex)
{
// 记录 ERP 数据转换异常,便于定位存储过程或序列化问题。
Gs.Toolbox.LogHelper.Debug(this.ToString(),
"EditModel isAdmin error:" + ex.Message);
}
Guid? guid = model.guid;
System.Text.StringBuilder stringBuilder =
new System.Text.StringBuilder();
// 采用 GUID 精确删除指定的查询数据源记录。
stringBuilder.Append("delete from FM_QUERY_TABLE where guid='" +
guid + "'");
rtnInt =
Gs.Toolbox.DbHelperSQL.ExecuteSql(stringBuilder.ToString());
if (rtnInt <= 0)
return ReturnDto.QuickReturn(rtnInt, ReturnCode.Exception,
"操作失败!");
return ReturnDto.QuickReturn(rtnInt, ReturnCode.Success,
"操作成功!");
}
///
/// 编辑列
///
///
///
[RequestMethod(RequestMethods.POST)]
public ReturnDto EditCol([FromBody] dynamic model)
{
int? rtnInt = (int)ReturnCode.Default;
int? isAdmin = 0;
try
{
isAdmin = chkAdmin();
if (isAdmin <= 0)
{
// 只有管理员才能调整查询列字段映射。
return ReturnDto.QuickReturn(rtnInt,
ReturnCode.Default, "你不是管理员,操作失败!");
}
}
catch (Exception ex)
{
// 记录 ERP 数据转换异常,便于定位存储过程或序列化问题。
Gs.Toolbox.LogHelper.Debug(this.ToString(),
"EditModel isAdmin error:" + ex.Message);
}
Guid? guid = model.guid;
string sqlField = model.sqlField;
string sqlFieldType = model.sqlFieldType;
string fType = model.fType;
System.Text.StringBuilder stringBuilder =
new System.Text.StringBuilder();
if (fType == "1")
stringBuilder.Append("update FM_QUERY set sqlFieldType='" +
sqlFieldType +
"', lastUpdateDate=getdate() where guid='" +
guid + "'");
else
stringBuilder.Append("update FM_QUERY set sqlField='" +
sqlField +
"', lastUpdateDate=getdate() where guid='" +
guid + "'");
rtnInt =
Gs.Toolbox.DbHelperSQL.ExecuteSql(stringBuilder.ToString());
if (rtnInt <= 0)
return ReturnDto.QuickReturn(rtnInt, ReturnCode.Exception,
"操作成功!");
return ReturnDto.QuickReturn(rtnInt, ReturnCode.Success,
"操作失败!");
}
#endregion
}
}