user.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. document.addEventListener('DOMContentLoaded', function() {
  2. // 确保在页面内容完全加载后执行
  3. console.log('user.js loaded');
  4. // 其他 JavaScript 代码
  5. });
  6. /*-------------------------------------------------- */
  7. // 统一的打开模态框函数
  8. function openModal(modalId) {
  9. const modal = document.getElementById(modalId);
  10. if (modal) {
  11. modal.style.display = "block"; // 显示模态框
  12. } else {
  13. console.error('模态框不存在,ID:', modalId);
  14. }
  15. }
  16. // 统一的关闭模态框函数
  17. function closeModal(modalId) {
  18. const modal = document.getElementById(modalId);
  19. if (modal) {
  20. modal.style.display = "none"; // 隐藏模态框
  21. } else {
  22. console.error('模态框不存在,ID:', modalId);
  23. }
  24. }
  25. // 点击"新增用户"按钮时,打开添加用户的模态框
  26. document.getElementById("addUserButton").addEventListener('click', function() {
  27. saveNewUserActionModal(); // 打开的是添加用户的模态框
  28. });
  29. /*-------------------------------------------------- */
  30. fetchUsers();
  31. function fetchUsers() {
  32. console.log('Fetching users...');
  33. fetch('http://127.0.0.1:8080/api/admin/userInfoAll', {
  34. method: 'GET',
  35. headers: {
  36. 'Authorization': `Bearer ${authToken}`,
  37. 'Content-Type': 'application/json'
  38. }
  39. })
  40. .then(response => response.json())
  41. .then(data => {
  42. const cardsContainer = document.querySelector('#users-cards');
  43. cardsContainer.innerHTML = ''; // 清空旧的卡片内容
  44. data.data.forEach(user => {
  45. if (user.Account === 'admin') {
  46. return;
  47. }
  48. const card = document.createElement('div');
  49. card.classList.add('user-info-card');
  50. card.innerHTML = `
  51. <div class="user-info-card-content">
  52. <p><strong>用户名:</strong> ${user.Username}</p>
  53. <p><strong>电话:</strong> ${user.Telephone}</p>
  54. <p><strong>邮箱:</strong> ${user.Email}</p>
  55. <p><strong>权限:</strong> ${user.Role}</p>
  56. <p><strong>账号:</strong> ${user.Account}</p>
  57. </div>
  58. `;
  59. card.addEventListener('click', (event) => {
  60. openUserActionModal(user);
  61. });
  62. cardsContainer.appendChild(card);
  63. });
  64. });
  65. }
  66. function openUserActionModal(user) {
  67. // 填充用户信息到模态框
  68. document.getElementById("modal-username").innerText = `用户名: ${user.Username}`;
  69. document.getElementById("modal-telephone").innerText = `电话: ${user.Telephone}`;
  70. document.getElementById("modal-email").innerText = `邮箱: ${user.Email}`;
  71. document.getElementById("modal-role").innerText = `权限: ${user.Role}`;
  72. document.getElementById("modal-account").innerText = `账号: ${user.Account}`;
  73. // 调用统一的 openModal 函数来显示模态框
  74. openModal('userActionModal');
  75. // 处理修改用户按钮点击
  76. document.getElementById("editUserButton").onclick = () => {
  77. closeModal("userActionModal"); // 先关闭用户信息模态框
  78. editUser(user); // 打开编辑用户模态框
  79. };
  80. // 处理删除用户按钮点击
  81. document.getElementById("deleteUserButton").onclick = () => {
  82. const userConfirmation = confirm("确定要删除该用户吗?");
  83. if (userConfirmation) {
  84. deleteUser(user);
  85. }
  86. };
  87. // 关闭模态框的点击事件(右上角关闭按钮)
  88. document.querySelector(".user-info-close").onclick = function() {
  89. closeModal("userActionModal"); // 使用封装好的 closeModal 函数
  90. };
  91. // 点击模态框外部时关闭模态框
  92. window.onclick = function(event) {
  93. const modal = document.getElementById("userActionModal");
  94. if (event.target === modal) {
  95. closeModal("userActionModal"); // 使用封装好的 closeModal 函数
  96. }
  97. };
  98. }
  99. //修改用户
  100. function editUser(user) {
  101. const modal = document.getElementById("editUserModal");
  102. const usernameInput = document.getElementById("username");
  103. const telephoneInput = document.getElementById("telephone");
  104. const emailInput = document.getElementById("email");
  105. const passwordInput = document.getElementById("password");
  106. const roleSelectDiv = document.getElementById("roleSelectDiv");
  107. const roleSelect = document.getElementById("role");
  108. // 填充用户信息
  109. usernameInput.value = user.Username;
  110. telephoneInput.value = user.Telephone;
  111. emailInput.value = user.Email;
  112. // 检查权限并填充角色选择框
  113. if (currentUserPermissions.includes('update_role')) {
  114. roleSelectDiv.style.display = "block";
  115. fetch('http://127.0.0.1:8080/api/admin/GetRoleNames', {
  116. method: 'GET',
  117. headers: {
  118. 'Authorization': `Bearer ${authToken}`,
  119. 'Content-Type': 'application/json'
  120. }
  121. })
  122. .then(response => response.json())
  123. .then(data => {
  124. roleSelect.innerHTML = ''; // 清空选项
  125. data.roles.forEach(role => {
  126. const option = document.createElement('option');
  127. option.value = role;
  128. option.textContent = role;
  129. if (user.Role === role) {
  130. option.selected = true;
  131. }
  132. roleSelect.appendChild(option);
  133. });
  134. })
  135. .catch(error => console.error('获取角色列表时出错:', error));
  136. } else {
  137. roleSelectDiv.style.display = "none";
  138. }
  139. // 显示编辑用户模态框
  140. modal.classList.add("show");
  141. // 关闭模态框事件
  142. document.getElementById("closeModalButton").onclick = () => {
  143. modal.classList.remove("show");
  144. };
  145. console.log("user",user);
  146. // 保存修改事件
  147. document.getElementById("saveChangesButton").onclick = () => {
  148. const updatedUser = {
  149. id: user.Id,
  150. unique_id : user.UniqueID,
  151. account: user.Account,
  152. username: usernameInput.value,
  153. telephone: telephoneInput.value,
  154. email: emailInput.value,
  155. password: passwordInput.value,
  156. role: roleSelect.value
  157. };
  158. // API 请求保存用户信息
  159. fetch('http://127.0.0.1:8080/api/admin/updateUser', {
  160. method: 'POST',
  161. headers: {
  162. 'Authorization': `Bearer ${authToken}`,
  163. 'Content-Type': 'application/json'
  164. },
  165. body: JSON.stringify(updatedUser)
  166. })
  167. .then(response => {
  168. if (response.ok) {
  169. console.log('用户信息保存成功');
  170. modal.classList.remove("show"); // 关闭模态框
  171. alert('用户信息修改成功!'); // 使用alert弹出提示
  172. fetchUsers();
  173. //window.location.reload(); // 刷新页面
  174. // 可以在这里添加成功提示
  175. } else {
  176. alert('用户信息修改失败:', response.statusText); // 使用alert弹出提示
  177. console.error('保存用户信息失败:', response.statusText);
  178. }
  179. })
  180. .catch(error => console.error('请求出错:', error));
  181. };
  182. }
  183. // 绑定按钮点击事件
  184. document.getElementById("editUserButton").onclick = () => {
  185. editUser(user);
  186. };
  187. //删除用户
  188. function deleteUser(user) {
  189. const uniqueID = user.UniqueID; // 获取用户的唯一ID
  190. fetch('http://127.0.0.1:8080/api/admin/deleteUser', {
  191. method: 'POST',
  192. headers: {
  193. 'Authorization': `Bearer ${authToken}`,
  194. 'Content-Type': 'application/json'
  195. },
  196. body: JSON.stringify({ UniqueID: uniqueID })
  197. })
  198. .then(response => response.json())
  199. .then(data => {
  200. if (data.success) {
  201. closeModal("userActionModal"); // 使用封装好的 closeModal 函数
  202. alert('用户删除成功!');
  203. fetchUsers(); // 重新加载用户列表
  204. } else {
  205. closeModal("userActionModal"); // 使用封装好的 closeModal 函数
  206. alert('用户删除失败:' + data.error);
  207. }
  208. })
  209. .catch(error => {
  210. console.error('删除用户时发生错误:', error);
  211. alert('删除用户时发生错误,请稍后再试。');
  212. });
  213. }
  214. // 保存新用户
  215. // 保存新用户的函数,并在适当的时候打开和关闭模态框
  216. function saveNewUserActionModal(user) {
  217. openModal('user-info-addUserModal'); // 打开的是添加用户的模态框
  218. // 点击模态框外部时关闭模态框
  219. window.onclick = function(event) {
  220. const modal = document.getElementById("user-info-addUserModal");
  221. if (event.target === modal) {
  222. closeModal("user-info-addUserModal"); // 使用封装好的 closeModal 函数
  223. }
  224. };
  225. }
  226. function saveNewUser() {
  227. const username = document.getElementById('user-info-addUsername').value.trim();
  228. const password = document.getElementById('user-info-addPassword').value.trim();
  229. const account = document.getElementById('user-info-addAccount').value.trim();
  230. const telephone = document.getElementById('user-info-addTelephone').value.trim();
  231. const email = document.getElementById('user-info-addEmail').value.trim();
  232. // 验证每个字段都不能为空
  233. if (!username || !password || !account || !telephone || !email) {
  234. alert('有空选项未填写');
  235. return;
  236. }
  237. // 验证电话是否为11位数字
  238. const phonePattern = /^\d{11}$/;
  239. if (!phonePattern.test(telephone)) {
  240. alert('电话必须是11位数字');
  241. return;
  242. }
  243. // 验证密码长度是否至少为6位
  244. if (password.length < 6) {
  245. alert('密码长度必须至少为6位');
  246. return;
  247. }
  248. // 验证邮箱是否包含@符号
  249. if (!email.includes('@')) {
  250. alert('邮箱必须包含@符号');
  251. return;
  252. }
  253. // 验证账号长度是否至少为3位
  254. if (account.length < 3) {
  255. alert('账号长度必须至少为3位');
  256. return;
  257. }
  258. // 构造新用户对象
  259. const newUser = {
  260. Username: username,
  261. Password: password,
  262. Account: account,
  263. Telephone: telephone,
  264. Email: email
  265. };
  266. // 发起请求保存新用户
  267. fetch('http://127.0.0.1:8080/api/register', { // 修改为实际的API路径
  268. method: 'POST',
  269. headers: {
  270. 'Authorization': `Bearer ${authToken}`, // 确保 authToken 是有效的
  271. 'Content-Type': 'application/json'
  272. },
  273. body: JSON.stringify(newUser)
  274. })
  275. .then(response => response.json())
  276. .then(data => {
  277. if (data.success) {
  278. alert('用户创建成功!');
  279. fetchUsers(); // 重新加载用户列表
  280. closeModal('user-info-addUserModal'); // 关闭模态框
  281. } else {
  282. alert('用户创建失败:' + data.error);
  283. }
  284. })
  285. .catch(error => {
  286. alert('请求失败:' + error);
  287. closeModal('user-info-addUserModal'); // 即使请求失败也可以选择关闭模态框
  288. });
  289. }