ProductCategory.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. <?php
  2. /**
  3. * 产品分类管理控制器
  4. */
  5. namespace app\admin\controller\product;
  6. use app\common\controller\Backend;
  7. use think\facade\Db;
  8. class ProductCategory extends Backend
  9. {
  10. /**
  11. * 分类列表(树形结构)
  12. * @return void
  13. */
  14. public function index()
  15. {
  16. $where = [];
  17. // 分类名称搜索
  18. if (!empty($this->request->get('name'))) {
  19. $name = $this->request->get('name');
  20. $where[] = ['name', 'like', '%' . $name . '%'];
  21. }
  22. // 状态筛选
  23. if (!empty($this->request->get('status'))) {
  24. $status = $this->request->get('status');
  25. $where['status'] = $status;
  26. }
  27. // 排序
  28. $order = [];
  29. if (!empty($this->request->get('order'))) {
  30. $order_a = $this->request->get('order');
  31. $order_a = explode(',', $order_a);
  32. $order[$order_a[0]] = $order_a[1];
  33. } else {
  34. $order['sort'] = 'asc';
  35. $order['id'] = 'asc';
  36. }
  37. // 查询所有分类
  38. $categoryList = Db::name('product_category')
  39. ->where($where)
  40. ->order($order)
  41. ->select()
  42. ->toArray();
  43. // 构建树形结构
  44. $tree = $this->buildTree($categoryList);
  45. $this->success('查询成功', $tree);
  46. }
  47. /**
  48. * 构建树形结构
  49. * @param array $items
  50. * @param int $parentId
  51. * @return array
  52. */
  53. private function buildTree(array $items, $parentId = 0)
  54. {
  55. $tree = [];
  56. foreach ($items as $item) {
  57. if ($item['parent_id'] == $parentId) {
  58. $children = $this->buildTree($items, $item['id']);
  59. if ($children) {
  60. $item['children'] = $children;
  61. }
  62. $tree[] = $item;
  63. }
  64. }
  65. return $tree;
  66. }
  67. /**
  68. * 新增/编辑分类
  69. * @return void
  70. */
  71. public function edit()
  72. {
  73. $id = $this->request->post('id');
  74. $name = $this->request->post('name');
  75. $parentId = $this->request->post('parent_id', 0);
  76. $icon = $this->request->post('icon', '');
  77. $sort = $this->request->post('sort', 0);
  78. $status = $this->request->post('status', 1);
  79. if (empty($name)) {
  80. $this->error(__('分类名称不能为空'));
  81. }
  82. // 验证分类名称是否已存在(同一父级下不能重复)
  83. $checkName = Db::name('product_category')
  84. ->where('name', $name)
  85. ->where('parent_id', $parentId);
  86. if (!empty($id)) {
  87. $checkName->where('id', '<>', $id);
  88. }
  89. if ($checkName->find()) {
  90. $this->error(__('同级分类下已存在相同名称'));
  91. }
  92. // 检查父级分类是否存在
  93. if ($parentId > 0) {
  94. $parentCategory = Db::name('product_category')
  95. ->where('id', $parentId)
  96. ->find();
  97. if (!$parentCategory) {
  98. $this->error(__('父级分类不存在'));
  99. }
  100. // 防止循环引用(不能将分类设置为自己的子分类)
  101. if (!empty($id) && $parentId == $id) {
  102. $this->error(__('不能将分类设置为自己的父级'));
  103. }
  104. }
  105. $data = [
  106. 'name' => $name,
  107. 'parent_id' => $parentId,
  108. 'icon' => $icon,
  109. 'sort' => $sort,
  110. 'status' => $status
  111. ];
  112. try {
  113. if (!empty($id)) {
  114. // 编辑
  115. $categoryInfo = Db::name('product_category')
  116. ->where('id', $id)
  117. ->find();
  118. if (!$categoryInfo) {
  119. $this->error(__('分类不存在'));
  120. }
  121. $result = Db::name('product_category')
  122. ->where('id', $id)
  123. ->update($data);
  124. $message = '编辑成功';
  125. } else {
  126. // 新增
  127. $data['create_time'] = date('Y-m-d H:i:s');
  128. $result = Db::name('product_category')
  129. ->insert($data);
  130. $id = Db::name('product_category')->getLastInsID();
  131. $message = '新增成功';
  132. }
  133. if ($result) {
  134. $this->success($message, ['id' => $id]);
  135. } else {
  136. $this->error(__('操作失败'));
  137. }
  138. } catch (\Exception $e) {
  139. $this->error('操作失败: ' . $e->getMessage());
  140. }
  141. }
  142. /**
  143. * 删除分类
  144. * @return void
  145. */
  146. public function delete()
  147. {
  148. $id = $this->request->post('id');
  149. if (empty($id)) {
  150. $this->error(__('参数错误'));
  151. }
  152. // 检查是否有子分类
  153. $hasChildren = Db::name('product_category')
  154. ->where('parent_id', $id)
  155. ->count();
  156. if ($hasChildren > 0) {
  157. $this->error(__('该分类下有子分类,请先删除子分类'));
  158. }
  159. // 检查是否有产品关联
  160. $hasProduct = Db::name('product')
  161. ->where('category_id', $id)
  162. ->count();
  163. if ($hasProduct > 0) {
  164. $this->error(__('该分类下有关联的产品,请先删除或转移产品'));
  165. }
  166. try {
  167. $result = Db::name('product_category')
  168. ->where('id', $id)
  169. ->delete();
  170. if ($result) {
  171. $this->success('删除成功');
  172. } else {
  173. $this->error(__('删除失败'));
  174. }
  175. } catch (\Exception $e) {
  176. $this->error('删除失败: ' . $e->getMessage());
  177. }
  178. }
  179. /**
  180. * 分类详情
  181. * @return void
  182. */
  183. public function detail()
  184. {
  185. $id = $this->request->get('id');
  186. if (empty($id)) {
  187. $this->error(__('参数错误'));
  188. }
  189. $categoryInfo = Db::name('product_category')
  190. ->where('id', $id)
  191. ->find();
  192. if (!$categoryInfo) {
  193. $this->error(__('分类不存在'));
  194. }
  195. // 获取父级分类信息
  196. if ($categoryInfo['parent_id'] > 0) {
  197. $parentInfo = Db::name('product_category')
  198. ->where('id', $categoryInfo['parent_id'])
  199. ->field('id, name')
  200. ->find();
  201. $categoryInfo['parent_info'] = $parentInfo;
  202. } else {
  203. $categoryInfo['parent_info'] = null;
  204. }
  205. // 统计子分类数量
  206. $childrenCount = Db::name('product_category')
  207. ->where('parent_id', $id)
  208. ->count();
  209. $categoryInfo['children_count'] = $childrenCount;
  210. // 统计产品数量
  211. $productCount = Db::name('product')
  212. ->where('category_id', $id)
  213. ->count();
  214. $categoryInfo['product_count'] = $productCount;
  215. $this->success('查询成功', $categoryInfo);
  216. }
  217. /**
  218. * 批量更新分类状态
  219. * @return void
  220. */
  221. public function batchStatus()
  222. {
  223. $ids = $this->request->post('ids');
  224. $status = $this->request->post('status');
  225. if (empty($ids) || empty($status)) {
  226. $this->error(__('参数错误'));
  227. }
  228. if (!is_array($ids)) {
  229. $ids = explode(',', $ids);
  230. }
  231. try {
  232. $result = Db::name('product_category')
  233. ->whereIn('id', $ids)
  234. ->update([
  235. 'status' => $status
  236. ]);
  237. if ($result) {
  238. $statusText = $status == 1 ? '启用' : '禁用';
  239. $this->success("成功{$statusText}{$result}个分类");
  240. } else {
  241. $this->error(__('操作失败'));
  242. }
  243. } catch (\Exception $e) {
  244. $this->error('操作失败: ' . $e->getMessage());
  245. }
  246. }
  247. /**
  248. * 获取分类下拉选项(用于选择父级分类)
  249. * @return void
  250. */
  251. public function selectOptions()
  252. {
  253. // 获取所有启用的分类
  254. $categoryList = Db::name('product_category')
  255. ->where('status', 1)
  256. ->order('sort', 'asc')
  257. ->order('id', 'asc')
  258. ->select()
  259. ->toArray();
  260. // 构建树形结构用于前端展示
  261. $tree = $this->buildTreeForSelect($categoryList);
  262. $this->success('查询成功', $tree);
  263. }
  264. /**
  265. * 构建用于下拉选择的树形结构
  266. * @param array $items
  267. * @param int $parentId
  268. * @param int $level
  269. * @return array
  270. */
  271. private function buildTreeForSelect(array $items, $parentId = 0, $level = 0)
  272. {
  273. $tree = [];
  274. $prefix = str_repeat(' ', $level * 2);
  275. foreach ($items as $item) {
  276. if ($item['parent_id'] == $parentId) {
  277. $item['label'] = ($level > 0 ? $prefix . '├─ ' : '') . $item['name'];
  278. $item['value'] = $item['id'];
  279. $children = $this->buildTreeForSelect($items, $item['id'], $level + 1);
  280. if ($children) {
  281. $item['children'] = $children;
  282. }
  283. $tree[] = $item;
  284. }
  285. }
  286. return $tree;
  287. }
  288. /**
  289. * 获取分类状态选项
  290. * @return void
  291. */
  292. public function statusOptions()
  293. {
  294. $options = [
  295. ['value' => 1, 'label' => '启用'],
  296. ['value' => 2, 'label' => '禁用']
  297. ];
  298. $this->success('获取成功', $options);
  299. }
  300. /**
  301. * 移动分类排序
  302. * @return void
  303. */
  304. public function moveSort()
  305. {
  306. $id = $this->request->post('id');
  307. $direction = $this->request->post('direction'); // up:上移, down:下移
  308. if (empty($id) || empty($direction)) {
  309. $this->error(__('参数错误'));
  310. }
  311. $categoryInfo = Db::name('product_category')
  312. ->where('id', $id)
  313. ->find();
  314. if (!$categoryInfo) {
  315. $this->error(__('分类不存在'));
  316. }
  317. try {
  318. Db::startTrans();
  319. // 获取同级分类
  320. $siblings = Db::name('product_category')
  321. ->where('parent_id', $categoryInfo['parent_id'])
  322. ->order('sort', 'asc')
  323. ->order('id', 'asc')
  324. ->select()
  325. ->toArray();
  326. // 找到当前分类在列表中的位置
  327. $currentIndex = -1;
  328. foreach ($siblings as $index => $sibling) {
  329. if ($sibling['id'] == $id) {
  330. $currentIndex = $index;
  331. break;
  332. }
  333. }
  334. if ($currentIndex === -1) {
  335. throw new \Exception('分类在同级中不存在');
  336. }
  337. if ($direction == 'up' && $currentIndex > 0) {
  338. // 上移:与上一个交换排序值
  339. $prevSibling = $siblings[$currentIndex - 1];
  340. Db::name('product_category')
  341. ->where('id', $id)
  342. ->update(['sort' => $prevSibling['sort']]);
  343. Db::name('product_category')
  344. ->where('id', $prevSibling['id'])
  345. ->update(['sort' => $categoryInfo['sort']]);
  346. } elseif ($direction == 'down' && $currentIndex < count($siblings) - 1) {
  347. // 下移:与下一个交换排序值
  348. $nextSibling = $siblings[$currentIndex + 1];
  349. Db::name('product_category')
  350. ->where('id', $id)
  351. ->update(['sort' => $nextSibling['sort']]);
  352. Db::name('product_category')
  353. ->where('id', $nextSibling['id'])
  354. ->update(['sort' => $categoryInfo['sort']]);
  355. } else {
  356. // 已经在最前或最后,无需移动
  357. Db::rollback();
  358. $this->success('无需移动');
  359. }
  360. Db::commit();
  361. $this->success('移动成功');
  362. } catch (\Exception $e) {
  363. Db::rollback();
  364. $this->error('移动失败: ' . $e->getMessage());
  365. }
  366. }
  367. }