| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547 |
- import React, { useState, useEffect, useRef, useMemo } from 'react';
- import { Plus, Search, RefreshCw, Edit2, Trash2 } from 'lucide-react';
- import { segregationPointApi, SegregationPointVO, PageParam } from '../api/spm/index';
- import { marsDeptApi, MarsDeptVO } from '../api/marsdept/index';
- import { lotoStationApi, LotoStationVO } from '../api/lotoStation/index';
- import { technologyApi, TechnologyVO } from '../api/technology/index';
- import { toast } from 'sonner';
- import { Modal, Table, Input, Button, Select, TreeSelect, Space, Image, Switch } from 'antd';
- import { ExclamationCircleOutlined } from '@ant-design/icons';
- import type { ColumnsType } from 'antd/es/table';
- import { handleTree } from '../utils/tree';
- import { getStrDictOptions, DICT_TYPE } from '../utils/dict';
- import SegregationPointForm, { SegregationPointFormRef } from './SegregationPointForm';
- import { Button as UIButton } from './ui/button';
- import PermissionWrapper from './PermissionWrapper';
- import { useTranslation } from 'react-i18next';
- interface SegregationPointManagementProps {
- subMenu?: string;
- }
- export default function SegregationPointManagement({ subMenu }: SegregationPointManagementProps) {
- const { t, i18n } = useTranslation();
- // 顶部查询条件:先隐藏(不删除代码),后续需要再打开改为 true 即可
- const showAdvancedQueryFilters = false;
- const [loading, setLoading] = useState(true);
- const [list, setList] = useState<SegregationPointVO[]>([]);
- const [total, setTotal] = useState(0);
- const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
- const [queryParams, setQueryParams] = useState<PageParam>({
- current: 1,
- size: 10,
- pointName: undefined,
- workstationId: undefined,
- machineryId: undefined,
- lotoId: undefined,
- powerType: undefined,
- });
- // 下拉选项数据
- const [deptOptions, setDeptOptions] = useState<any[]>([]);
- const [machineryOptions, setMachineryOptions] = useState<any[]>([]);
- const [lotoOptions, setLotoOptions] = useState<Array<{ label: string; value: number }>>([]);
- const powerTypeOptions = getStrDictOptions(DICT_TYPE.POWER_TYPE);
- const formRef = useRef<SegregationPointFormRef>(null);
- // 获取隔离点列表
- const getList = async (params?: PageParam) => {
- const currentParams = params || queryParams;
- setLoading(true);
- try {
- console.log('SegregationPointManagement: 开始获取隔离点列表', currentParams);
- const response = await segregationPointApi.getIsIsolationPointPage(currentParams);
- console.log('SegregationPointManagement: API 响应', response);
-
- // 处理响应数据
- let data;
- if (response && typeof response === 'object') {
- // 如果响应有 data 属性,使用 data;否则直接使用 response
- if ('data' in response && response.data) {
- data = response.data;
- } else if ('list' in response || 'total' in response) {
- data = response;
- } else {
- data = response;
- }
- } else {
- data = response;
- }
-
- setList(data?.list || []);
- setTotal(data?.total || 0);
- console.log('SegregationPointManagement: 设置列表数据', { list: data?.list || [], total: data?.total || 0 });
- } catch (error: any) {
- console.error('SegregationPointManagement: 获取列表失败', error);
- toast.error(error.message || t('form.getSegregationPointListFailed'));
- } finally {
- setLoading(false);
- }
- };
- useEffect(() => {
- getList();
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [queryParams.current, queryParams.size]);
- // 初始化数据
- useEffect(() => {
- const initData = async () => {
- try {
- // 获取岗位数据
- const deptRes = await marsDeptApi.listMarsDept({ pageNo: 1, pageSize: -1 });
- const deptTreeData = handleTree(deptRes.list, 'id', 'parentId');
- setDeptOptions(convertToTreeSelectData(deptTreeData, 'workstationName'));
- // 获取锁定站数据
- try {
- const lotoRes = await lotoStationApi.listLoto({ pageNo: 1, pageSize: -1 });
- const data = (lotoRes as any)?.data || lotoRes;
- const lotoList = data?.list || [];
- setLotoOptions(lotoList.map((item: any) => ({
- value: item.id!,
- label: item.lotoName,
- })));
- } catch (lotoError) {
- console.error('获取锁定站数据失败:', lotoError);
- // 锁定站是非必填的,如果接口不存在或失败,设置为空数组即可
- setLotoOptions([]);
- }
- // 获取设备/工艺数据
- const techRes = await technologyApi.listTechnology({ pageNo: 1, pageSize: -1 });
- const techData = techRes.list.filter(item => item.machineryType === '工艺');
- const techTreeData = handleTree(techData, 'id', 'parentId');
- setMachineryOptions(convertToTreeSelectData(techTreeData, 'machineryName'));
- } catch (error) {
- console.error('初始化数据失败:', error);
- }
- };
- initData();
- }, []);
- // 转换树形数据为 TreeSelect 格式
- const convertToTreeSelectData = (treeData: any[], labelKey: string): any[] => {
- return treeData.map(item => ({
- title: item[labelKey],
- value: item.id,
- key: item.id,
- children: item.children ? convertToTreeSelectData(item.children, labelKey) : undefined,
- }));
- };
- // 搜索
- const handleQuery = () => {
- setQueryParams({ ...queryParams, current: 1 });
- getList({ ...queryParams, current: 1 });
- };
- // 重置搜索
- const resetQuery = () => {
- const resetParams: PageParam = {
- current: 1,
- size: 10,
- pointName: undefined,
- workstationId: undefined,
- machineryId: undefined,
- lotoId: undefined,
- powerType: undefined,
- };
- setQueryParams(resetParams);
- getList(resetParams);
- };
- // 打开表单
- const openForm = (type: string, id?: number) => {
- formRef.current?.open(type, id);
- };
- // 删除隔离点
- const handleDelete = async (id?: number) => {
- const pointIds = id ? [id] : selectedRowKeys.map(key => Number(key));
-
- Modal.confirm({
- title: t('common.confirmDelete'),
- icon: <ExclamationCircleOutlined />,
- content: `${t('common.confirmDeleteText')} ${pointIds.length} ${t('common.records')}?`,
- okText: t('common.confirmDelete'),
- okType: 'danger',
- cancelText: t('common.cancel'),
- onOk: async () => {
- try {
- await segregationPointApi.deleteIsIsolationPointByPointIds(pointIds);
- toast.success(t('common.deleteSuccess'));
- setSelectedRowKeys([]);
- await getList();
- } catch (error: any) {
- toast.error(error.message || t('common.deleteFailed'));
- }
- },
- });
- };
- // 表格列配置
- const columns: ColumnsType<SegregationPointVO> = useMemo(() => [
- {
- title: t('table.segregationPointId'),
- dataIndex: 'id',
- width: 100,
- align: 'center',
- },
- {
- title: t('table.segregationPointName'),
- dataIndex: 'pointName',
- align: 'center',
- },
- {
- title: t('table.icon'),
- dataIndex: 'pointIcon',
- width: 100,
- align: 'center',
- render: (text: string) => {
- if (text) {
- return <Image src={text} width={50} height={50} style={{ objectFit: 'cover' }} />;
- }
- return '-';
- },
- },
- {
- title: t('table.switchStatus'),
- dataIndex: 'switchStatus',
- width: 100,
- align: 'center',
- render: (status: number | string | null) => {
- if (status === null || status === undefined) {
- return '-';
- }
- const isChecked = String(status) === '1';
- return (
- <Switch
- checked={isChecked}
- checkedChildren="ON"
- unCheckedChildren="OFF"
- disabled
- style={{ pointerEvents: 'none' }}
- />
- );
- },
- },
- {
- title: t('table.segregationPointNfc'),
- dataIndex: 'pointNfc',
- align: 'center',
- },
- {
- title: t('table.position'),
- dataIndex: 'workstationName',
- align: 'center',
- },
- {
- title: t('table.deviceProcess'),
- dataIndex: 'machineryName',
- width: 180,
- align: 'center',
- },
- {
- title: t('table.lotoStation'),
- dataIndex: 'lotoName',
- width: 120,
- align: 'center',
- },
- {
- title: t('table.segregationPointSerial'),
- dataIndex: 'pointSerialNumber',
- width: 120,
- align: 'center',
- },
- {
- title: t('table.function'),
- dataIndex: 'remark',
- align: 'center',
- },
- {
- title: t('table.image'),
- dataIndex: 'pointPicture',
- width: 100,
- align: 'center',
- render: (text: string) => {
- if (text) {
- return <Image src={text} width={50} height={50} style={{ objectFit: 'cover' }} />;
- }
- return '-';
- },
- },
- {
- title: t('table.energySource'),
- dataIndex: 'powerType',
- align: 'center',
- render: (value: string) => {
- const option = powerTypeOptions.find(opt => opt.value === value);
- return option ? option.label : value || '-';
- },
- },
- {
- title: t('table.operation'),
- width: 150,
- align: 'center',
- fixed: 'right',
- render: (_: any, record: SegregationPointVO) => (
- <div className="flex items-center gap-2 justify-center">
- <PermissionWrapper permission="iscs:point:update">
- <UIButton
- variant="ghost"
- size="sm"
- onClick={() => openForm('update', record.pointId)}
- className="h-8 px-2 transition-colors hover:underline"
- style={{ color: '#000000' }}
- onMouseEnter={(e) => {
- e.currentTarget.style.color = '#1677ff';
- e.currentTarget.style.textDecoration = 'underline';
- e.currentTarget.querySelector('svg')?.setAttribute('style', 'color: #1677ff');
- }}
- onMouseLeave={(e) => {
- e.currentTarget.style.color = '#000000';
- e.currentTarget.style.textDecoration = 'none';
- e.currentTarget.querySelector('svg')?.setAttribute('style', 'color: #000000');
- }}
- >
- <Edit2 className="w-4 h-4" style={{ color: '#000000' }} />
- <span className="ml-1">{t('common.edit')}</span>
- </UIButton>
- </PermissionWrapper>
- <PermissionWrapper permission="iscs:point:delete">
- <UIButton
- variant="ghost"
- size="sm"
- onClick={() => handleDelete(record.pointId)}
- className="h-8 px-2 transition-colors hover:underline"
- style={{ color: '#000000' }}
- onMouseEnter={(e) => {
- e.currentTarget.style.color = '#1677ff';
- e.currentTarget.style.textDecoration = 'underline';
- e.currentTarget.querySelector('svg')?.setAttribute('style', 'color: #1677ff');
- }}
- onMouseLeave={(e) => {
- e.currentTarget.style.color = '#000000';
- e.currentTarget.style.textDecoration = 'none';
- e.currentTarget.querySelector('svg')?.setAttribute('style', 'color: #000000');
- }}
- >
- <Trash2 className="w-4 h-4" style={{ color: '#000000' }} />
- <span className="ml-1">{t('common.delete')}</span>
- </UIButton>
- </PermissionWrapper>
- </div>
- ),
- },
- ], [t, i18n.language, powerTypeOptions]);
- return (
- <div className="p-6 space-y-4">
- {/* 搜索栏 */}
- <div className="bg-white rounded-xl border border-gray-200/50 shadow-sm p-5">
- <div className="flex flex-col gap-4">
- {/* 搜索字段 + 操作按钮:同一行,按钮靠右 */}
- <div className="flex items-center justify-between gap-3 flex-wrap">
- <div className="flex items-center gap-3 flex-wrap">
- <div className="flex items-center gap-2">
- <label className="text-sm font-medium text-gray-700 whitespace-nowrap">{t('form.segregationPointName')}:</label>
- <Input
- value={queryParams.pointName}
- onChange={(e) => setQueryParams({ ...queryParams, pointName: e.target.value })}
- onPressEnter={handleQuery}
- placeholder={t('form.segregationPointNamePlaceholder')}
- className="w-[180px]"
- allowClear
- />
- </div>
- {showAdvancedQueryFilters && (
- <>
- <div className="flex items-center gap-2">
- <label className="text-sm font-medium text-gray-700 whitespace-nowrap">{t('form.workstation')}:</label>
- <TreeSelect
- value={queryParams.workstationId}
- onChange={(value) => setQueryParams({ ...queryParams, workstationId: value })}
- treeData={deptOptions}
- placeholder={t('form.workstationPlaceholder')}
- allowClear
- className="w-[180px]"
- />
- </div>
- <div className="flex items-center gap-2">
- <label className="text-sm font-medium text-gray-700 whitespace-nowrap">{t('form.deviceProcess')}:</label>
- <TreeSelect
- value={queryParams.machineryId}
- onChange={(value) => setQueryParams({ ...queryParams, machineryId: value })}
- treeData={machineryOptions}
- placeholder={t('form.deviceProcessPlaceholder')}
- allowClear
- className="w-[180px]"
- />
- </div>
- <div className="flex items-center gap-2">
- <label className="text-sm font-medium text-gray-700 whitespace-nowrap">{t('form.lotoStation')}:</label>
- <Select
- value={queryParams.lotoId}
- onChange={(value) => setQueryParams({ ...queryParams, lotoId: value })}
- placeholder={t('form.lotoStationPlaceholder')}
- allowClear
- className="w-[180px]"
- options={lotoOptions}
- />
- </div>
- <div className="flex items-center gap-2">
- <label className="text-sm font-medium text-gray-700 whitespace-nowrap">{t('form.energySource')}:</label>
- <Select
- value={queryParams.powerType}
- onChange={(value) => setQueryParams({ ...queryParams, powerType: value })}
- placeholder={t('form.energySourcePlaceholder')}
- allowClear
- className="w-[180px]"
- options={powerTypeOptions}
- />
- </div>
- </>
- )}
- </div>
- <div className="flex justify-end">
- <Space>
- <PermissionWrapper permission="iscs:point:query">
- <Button
- type="primary"
- icon={<Search />}
- onClick={handleQuery}
- >
- {t('common.search')}
- </Button>
- </PermissionWrapper>
- <PermissionWrapper permission="iscs:point:query">
- <Button
- icon={<RefreshCw />}
- onClick={resetQuery}
- >
- {t('common.reset')}
- </Button>
- </PermissionWrapper>
- <PermissionWrapper permission="iscs:point:create">
- <Button
- type="primary"
- icon={<Plus />}
- onClick={() => openForm('create')}
- >
- {t('common.addNew')}
- </Button>
- </PermissionWrapper>
- <PermissionWrapper permission="iscs:point:delete">
- <Button
- danger
- icon={<Trash2 className="w-4 h-4" />}
- disabled={selectedRowKeys.length === 0}
- onClick={() => handleDelete()}
- >
- {t('common.batchDelete')}
- </Button>
- </PermissionWrapper>
- </Space>
- </div>
- </div>
- </div>
- </div>
- {/* 表格 */}
- <div className="bg-white rounded-lg border border-gray-200">
- <Table
- columns={columns}
- dataSource={list}
- rowKey={(record, index) => {
- // 优先使用 pointId,如果没有则使用 id,最后使用索引
- const key = record.pointId ?? record.id ?? `row-${index}`;
- return key;
- }}
- loading={loading}
- pagination={false}
- scroll={{ x: 'max-content' }}
- rowSelection={{
- selectedRowKeys,
- onChange: (keys) => {
- setSelectedRowKeys(keys);
- },
- onSelect: (record, selected) => {
- const recordKey = record.pointId ?? record.id;
- if (!recordKey) return;
-
- if (selected) {
- // 选中时,只添加当前行的 key
- setSelectedRowKeys(prev => {
- if (prev.includes(recordKey)) {
- return prev;
- }
- return [...prev, recordKey];
- });
- } else {
- // 取消选中时,只移除当前行的 key
- setSelectedRowKeys(prev => prev.filter(key => key !== recordKey));
- }
- },
- onSelectAll: (selected, selectedRows, changeRows) => {
- if (selected) {
- // 全选时,只选中当前页的数据
- const currentPageKeys = list
- .map(item => item.pointId ?? item.id)
- .filter((id): id is number => id !== undefined && id !== null);
- setSelectedRowKeys(prev => {
- const newKeys = new Set(prev);
- currentPageKeys.forEach(key => newKeys.add(key));
- return Array.from(newKeys);
- });
- } else {
- // 取消全选时,只取消当前页的选中
- const currentPageKeys = list
- .map(item => item.pointId ?? item.id)
- .filter((id): id is number => id !== undefined && id !== null);
- setSelectedRowKeys(prev => prev.filter(key => !currentPageKeys.includes(key)));
- }
- },
- getCheckboxProps: (record) => ({
- name: record.pointName,
- }),
- }}
- />
- </div>
- {/* 分页 */}
- {!loading && list.length > 0 && (
- <div className="bg-white rounded-lg border border-gray-200 px-6 py-4">
- <div className="flex items-center justify-between">
- <div className="text-sm text-gray-600">
- {t('common.total')} <span className="text-blue-600 font-medium">{total}</span> {t('common.records')}
- </div>
- <div className="flex gap-2">
- <Button
- onClick={() => setQueryParams({ ...queryParams, current: (queryParams.current || 1) - 1 })}
- disabled={(queryParams.current || 1) <= 1}
- >
- {t('common.prevPage')}
- </Button>
- <span className="px-4 py-2 text-sm text-gray-600 flex items-center">
- {queryParams.current || 1} / {Math.ceil(total / (queryParams.size || 10)) || 1}
- </span>
- <Button
- onClick={() => setQueryParams({ ...queryParams, current: (queryParams.current || 1) + 1 })}
- disabled={(queryParams.current || 1) >= Math.ceil(total / (queryParams.size || 10))}
- >
- {t('common.nextPage')}
- </Button>
- </div>
- </div>
- </div>
- )}
- {/* 表单弹窗 */}
- <SegregationPointForm ref={formRef} onSuccess={getList} />
- </div>
- );
- }
|