cargo_tab.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. """
  2. 货物维护Tab页面
  3. """
  4. from PyQt5.QtWidgets import (
  5. QWidget, QVBoxLayout, QHBoxLayout, QLabel, QLineEdit, QPushButton,
  6. QTableWidget, QTableWidgetItem, QHeaderView, QMessageBox, QDialog,
  7. QFormLayout
  8. )
  9. from PyQt5.QtCore import Qt, QTimer
  10. from PyQt5.QtGui import QFont
  11. import time
  12. import logging
  13. from typing import Optional, Dict
  14. from database import Database
  15. from .button_styles import apply_button_style
  16. startup_logger = logging.getLogger('startup')
  17. class CargoTab(QWidget):
  18. """货物维护Tab"""
  19. def __init__(self, db: Database, current_user: Optional[Dict] = None):
  20. tab_start = time.time()
  21. super().__init__()
  22. self.db = db
  23. self.current_cargos = []
  24. self.current_user = current_user or {}
  25. self._is_admin = self.current_user.get('role') == 'admin'
  26. ui_start = time.time()
  27. self.init_ui()
  28. startup_logger.info(f" 界面初始化 (耗时: {time.time() - ui_start:.3f}秒)")
  29. refresh_start = time.time()
  30. self.refresh_list()
  31. startup_logger.info(f" 数据加载 (耗时: {time.time() - refresh_start:.3f}秒)")
  32. def init_ui(self):
  33. """初始化界面"""
  34. layout = QVBoxLayout()
  35. layout.setSpacing(10)
  36. layout.setContentsMargins(15, 15, 15, 15)
  37. # 标题
  38. title = QLabel("货物名称维护")
  39. title_font = QFont("微软雅黑", 18, QFont.Bold)
  40. title.setFont(title_font)
  41. layout.addWidget(title)
  42. # 按钮区域
  43. button_layout = QHBoxLayout()
  44. button_layout.setSpacing(10)
  45. self.add_btn = QPushButton("新增")
  46. self.add_btn.setMinimumHeight(45)
  47. self.add_btn.setMinimumWidth(120)
  48. self.add_btn.setFont(QFont("微软雅黑", 16))
  49. apply_button_style(self.add_btn, 'green')
  50. self.add_btn.clicked.connect(self.add_cargo)
  51. # 添加快捷键
  52. from PyQt5.QtGui import QKeySequence
  53. self.add_btn.setShortcut(QKeySequence("Ctrl+N"))
  54. self.edit_btn = QPushButton("修改")
  55. self.edit_btn.setMinimumHeight(45)
  56. self.edit_btn.setMinimumWidth(120)
  57. self.edit_btn.setFont(QFont("微软雅黑", 16))
  58. apply_button_style(self.edit_btn, 'normal')
  59. self.edit_btn.clicked.connect(self.edit_cargo)
  60. self.delete_btn = QPushButton("删除")
  61. self.delete_btn.setMinimumHeight(45)
  62. self.delete_btn.setMinimumWidth(120)
  63. self.delete_btn.setFont(QFont("微软雅黑", 16))
  64. apply_button_style(self.delete_btn, 'normal')
  65. self.delete_btn.clicked.connect(self.delete_cargo)
  66. # 添加快捷键(仅管理员可用)
  67. from PyQt5.QtGui import QKeySequence
  68. if self._is_admin:
  69. self.delete_btn.setShortcut(QKeySequence("Delete"))
  70. else:
  71. self.delete_btn.hide()
  72. self.delete_btn.setEnabled(False)
  73. self.refresh_btn = QPushButton("刷新")
  74. self.refresh_btn.setMinimumHeight(45)
  75. self.refresh_btn.setMinimumWidth(120)
  76. self.refresh_btn.setFont(QFont("微软雅黑", 16))
  77. apply_button_style(self.refresh_btn, 'normal')
  78. self.refresh_btn.setEnabled(True) # 确保按钮是启用状态
  79. self.refresh_btn.clicked.connect(self.refresh_list)
  80. self.refresh_btn.setShortcut(QKeySequence("F5"))
  81. button_layout.addWidget(self.add_btn)
  82. button_layout.addWidget(self.edit_btn)
  83. button_layout.addWidget(self.delete_btn)
  84. button_layout.addWidget(self.refresh_btn)
  85. button_layout.addStretch()
  86. layout.addLayout(button_layout)
  87. # 表格
  88. self.table = QTableWidget()
  89. self.table.setColumnCount(1)
  90. self.table.setHorizontalHeaderLabels(["货物名称"])
  91. header = self.table.horizontalHeader()
  92. header.setFont(QFont("微软雅黑", 15, QFont.Bold))
  93. header.setSectionsMovable(False)
  94. header.setStretchLastSection(False)
  95. header.setSectionsClickable(False)
  96. self.column_width_ratios = [1.0]
  97. self._user_resized_columns = False
  98. self._is_applying_column_widths = False
  99. header.setSectionResizeMode(0, QHeaderView.Interactive)
  100. header.sectionResized.connect(self._on_section_resized)
  101. self._apply_table_column_widths(force=True)
  102. vertical_header = self.table.verticalHeader()
  103. vertical_header.setDefaultAlignment(Qt.AlignCenter)
  104. vertical_header.setFixedWidth(60)
  105. vertical_header.setSectionResizeMode(QHeaderView.ResizeToContents)
  106. self.table.setFont(QFont("微软雅黑", 15))
  107. self.table.setAlternatingRowColors(True)
  108. self.table.setSelectionBehavior(QTableWidget.SelectRows)
  109. self.table.setSelectionMode(QTableWidget.SingleSelection)
  110. layout.addWidget(self.table)
  111. self.setLayout(layout)
  112. def refresh_list(self):
  113. """刷新列表"""
  114. cargos = self.db.get_all_cargos()
  115. self.current_cargos = cargos
  116. self.table.setRowCount(len(cargos))
  117. for i, cargo in enumerate(cargos):
  118. # 货物名称
  119. self.table.setItem(i, 0, QTableWidgetItem(cargo['name']))
  120. self.table.resizeRowsToContents()
  121. QTimer.singleShot(0, self.table.resizeRowsToContents)
  122. def get_selected_cargo_id(self) -> int:
  123. """获取选中的货物ID"""
  124. current_row = self.table.currentRow()
  125. if current_row < 0:
  126. return -1
  127. cargos = getattr(self, 'current_cargos', [])
  128. if current_row >= len(cargos):
  129. return -1
  130. return cargos[current_row]['id']
  131. def add_cargo(self):
  132. """新增货物"""
  133. dialog = CargoDialog(self.db, parent=self)
  134. if dialog.exec_() == QDialog.Accepted:
  135. self.refresh_list()
  136. def edit_cargo(self):
  137. """修改货物"""
  138. cargo_id = self.get_selected_cargo_id()
  139. if cargo_id < 0:
  140. QMessageBox.warning(self, "提示", "请先选择要修改的货物")
  141. return
  142. cargos = getattr(self, 'current_cargos', [])
  143. cargo = next((c for c in cargos if c['id'] == cargo_id), None)
  144. if not cargo:
  145. QMessageBox.warning(self, "错误", "未找到该货物")
  146. return
  147. dialog = CargoDialog(self.db, cargo=cargo, parent=self)
  148. if dialog.exec_() == QDialog.Accepted:
  149. self.refresh_list()
  150. def delete_cargo(self):
  151. """删除货物"""
  152. if not self._is_admin:
  153. QMessageBox.warning(self, "权限不足", "仅管理员可执行删除。")
  154. return
  155. cargo_id = self.get_selected_cargo_id()
  156. if cargo_id < 0:
  157. QMessageBox.warning(self, "提示", "请先选择要删除的货物")
  158. return
  159. # 确认删除
  160. msg = QMessageBox()
  161. msg.setIcon(QMessageBox.Question)
  162. msg.setWindowTitle("确认")
  163. msg.setText("确定要删除该货物吗?")
  164. msg.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
  165. msg.setDefaultButton(QMessageBox.No)
  166. msg.button(QMessageBox.Yes).setText("是")
  167. msg.button(QMessageBox.No).setText("否")
  168. reply = msg.exec_()
  169. if reply == QMessageBox.Yes:
  170. if self.db.delete_cargo(cargo_id):
  171. QMessageBox.information(self, "成功", "删除成功!")
  172. self.refresh_list()
  173. else:
  174. QMessageBox.warning(self, "错误", "删除失败")
  175. def resizeEvent(self, event):
  176. super().resizeEvent(event)
  177. self._apply_table_column_widths()
  178. def showEvent(self, event):
  179. super().showEvent(event)
  180. QTimer.singleShot(0, lambda: self._apply_table_column_widths(force=True))
  181. def _on_section_resized(self, *_):
  182. if getattr(self, "_is_applying_column_widths", False):
  183. return
  184. self._user_resized_columns = True
  185. def _apply_table_column_widths(self, force: bool = False):
  186. if not hasattr(self, "table") or not hasattr(self, "column_width_ratios"):
  187. return
  188. if self._user_resized_columns and not force:
  189. return
  190. viewport_width = self.table.viewport().width()
  191. if viewport_width <= 0:
  192. return
  193. total_ratio = sum(self.column_width_ratios) or 1
  194. assigned_width = 0
  195. header = self.table.horizontalHeader()
  196. self._is_applying_column_widths = True
  197. header.blockSignals(True)
  198. try:
  199. for index, ratio in enumerate(self.column_width_ratios):
  200. if index == self.table.columnCount() - 1:
  201. width = viewport_width - assigned_width
  202. else:
  203. width = int(viewport_width * ratio / total_ratio)
  204. assigned_width += width
  205. self.table.setColumnWidth(index, max(width, 50))
  206. finally:
  207. header.blockSignals(False)
  208. self._is_applying_column_widths = False
  209. class CargoDialog(QDialog):
  210. """货物编辑对话框"""
  211. def __init__(self, db: Database, cargo=None, parent=None):
  212. super().__init__(parent)
  213. self.db = db
  214. self.cargo = cargo
  215. self.init_ui()
  216. def init_ui(self):
  217. """初始化对话框界面"""
  218. if self.cargo:
  219. self.setWindowTitle("修改货物名称")
  220. else:
  221. self.setWindowTitle("新增货物名称")
  222. self.setMinimumWidth(400)
  223. layout = QVBoxLayout()
  224. layout.setSpacing(15)
  225. layout.setContentsMargins(20, 20, 20, 20)
  226. # 表单
  227. form_layout = QFormLayout()
  228. form_layout.setSpacing(15)
  229. name_label = QLabel("货物名称 *:")
  230. name_label.setFont(QFont("微软雅黑", 16))
  231. self.name_input = QLineEdit()
  232. self.name_input.setMinimumHeight(45)
  233. self.name_input.setFont(QFont("微软雅黑", 16))
  234. if self.cargo:
  235. self.name_input.setText(self.cargo['name'])
  236. form_layout.addRow(name_label, self.name_input)
  237. layout.addLayout(form_layout)
  238. # 按钮
  239. button_layout = QHBoxLayout()
  240. button_layout.addStretch()
  241. ok_btn = QPushButton("确定")
  242. ok_btn.setMinimumHeight(45)
  243. ok_btn.setMinimumWidth(100)
  244. ok_btn.setFont(QFont("微软雅黑", 16))
  245. apply_button_style(ok_btn, 'green')
  246. ok_btn.clicked.connect(self.save)
  247. cancel_btn = QPushButton("取消")
  248. cancel_btn.setMinimumHeight(45)
  249. cancel_btn.setMinimumWidth(100)
  250. cancel_btn.setFont(QFont("微软雅黑", 16))
  251. apply_button_style(cancel_btn, 'normal')
  252. cancel_btn.clicked.connect(self.reject)
  253. button_layout.addWidget(ok_btn)
  254. button_layout.addWidget(cancel_btn)
  255. layout.addLayout(button_layout)
  256. self.setLayout(layout)
  257. def save(self):
  258. """保存"""
  259. name = self.name_input.text().strip()
  260. if not name:
  261. QMessageBox.warning(self, "验证失败", "货物名称不能为空")
  262. return
  263. # 检查重复
  264. if self.cargo:
  265. # 修改模式
  266. if self.db.cargo_exists(name, exclude_id=self.cargo['id']):
  267. QMessageBox.warning(self, "验证失败", "该名称已存在")
  268. return
  269. if self.db.update_cargo(self.cargo['id'], name):
  270. QMessageBox.information(self, "成功", "修改成功!")
  271. self.accept()
  272. else:
  273. QMessageBox.warning(self, "错误", "修改失败")
  274. else:
  275. # 新增模式
  276. if self.db.cargo_exists(name):
  277. QMessageBox.warning(self, "验证失败", "该名称已存在")
  278. return
  279. try:
  280. self.db.insert_cargo(name)
  281. QMessageBox.information(self, "成功", "新增成功!")
  282. self.accept()
  283. except Exception as e:
  284. QMessageBox.critical(self, "错误", f"新增失败:{str(e)}")