ERPHelper.cs 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. using JLHHJSvr.BLL;
  2. using JLHHJSvr.Com.Model;
  3. using JLHHJSvr.LJException;
  4. using Newtonsoft.Json.Linq;
  5. using System;
  6. using System.Collections;
  7. using System.Collections.Generic;
  8. using System.Linq;
  9. using System.Text;
  10. using System.Threading.Tasks;
  11. namespace JLHHJSvr.Helper
  12. {
  13. internal class ERPHelper : HelperBase
  14. {
  15. private JObject BuildLoginRequest()
  16. {
  17. return new JObject
  18. {
  19. { "token", GlobalVar.ERP_TOKEN },
  20. { "account", GlobalVar.ERP_ACCOUNT_NAME },
  21. { "userid", GlobalVar.ERP_ACCOUNT_USERNAME },
  22. { "password", GlobalVar.ERP_ACCOUNT_PASSWORD },
  23. { "clientType", 30 }
  24. };
  25. }
  26. private static readonly Dictionary<string, string> _apiResultMap = new Dictionary<string, string>()
  27. {
  28. {"GetL1Mtrldef", "mtrldefList"},
  29. {"GetSCWorkgroupList", "scworkgroupList"},
  30. {"GetL1Mtrltype", "mtrltypeList"},
  31. {"CommonDynamicSelect", "datatable"}
  32. };
  33. protected void Login()
  34. {
  35. var request = BuildLoginRequest();
  36. try
  37. {
  38. var result = DoExecute("Login", request);
  39. var token = result.GetValue("token").ToObject<string>();
  40. if (!string.IsNullOrEmpty(token))
  41. {
  42. GlobalVar.ERP_TOKEN = token;
  43. }
  44. }
  45. catch (Exception ex)
  46. {
  47. throw new LJCommonException($"ERP登录失败: {ex.Message}");
  48. }
  49. }
  50. public void CheckLogin()
  51. {
  52. if(string.IsNullOrEmpty(GlobalVar.ERP_TOKEN))
  53. {
  54. Login();
  55. }
  56. }
  57. public List<T> GetERPList<T>(string apiMethod, JObject parameters = null, int tryCnt = 0)
  58. {
  59. CheckLogin();
  60. try
  61. {
  62. var request = BuildRequest(parameters);
  63. var result = DoExecute(apiMethod, request);
  64. if (!_apiResultMap.TryGetValue(apiMethod, out var listKey)) throw new ArgumentException($"Unsupported API Method: {apiMethod}");
  65. return result[listKey]?.ToObject<List<T>>() ?? new List<T>();
  66. }
  67. catch (Exception ex) when (IsTokenExpired(ex))
  68. {
  69. if (tryCnt >= 3) throw new LJCommonException("超过最大重连次数,请检查连接!");
  70. Login();
  71. return GetERPList<T>(apiMethod, parameters, tryCnt + 1);
  72. }
  73. catch
  74. {
  75. throw;
  76. }
  77. }
  78. // 提取请求构建逻辑
  79. private JObject BuildRequest(JObject parameters)
  80. {
  81. var request = new JObject { ["token"] = GlobalVar.ERP_TOKEN };
  82. parameters = parameters ?? new JObject();
  83. foreach (var param in parameters)
  84. {
  85. request.Add(param.Key, param.Value);
  86. }
  87. return request;
  88. }
  89. private bool IsTokenExpired(Exception ex)
  90. {
  91. const string expiredFlag = "已与服务器失联";
  92. return ex.Message.Contains(expiredFlag);
  93. }
  94. }
  95. }