import React, { useState, useRef, useEffect } from 'react';
import {
Form, Select, Button, Space, message, Card, Typography,
Row, Col, Modal, Input, Table, Popconfirm, Checkbox
} from 'antd';
import QRCode from 'qrcode';
import DictManager from "../DictManager";
import request from '../../api/request';
import { Country, State } from 'country-state-city';
// 接口导入
import {
getRobotTypeListApi,
addRobotTypeApi,
updateRobotTypeApi,
deleteRobotTypeApi,
getRobotModelPageApi,
addRobotModelApi,
updateRobotModelApi,
deleteRobotModelApi,
getRobotConfigListApi,
addRobotConfigApi,
updateRobotConfigApi,
deleteRobotConfigApi,
saveCodeApi,
getCodeImgApi,
getCodeListApi,
getCodeListPageApi,
getCodeDeatil,
delteCodesApi
} from '../../api/systemSetting';
const { Text } = Typography;
const { Option } = Select;
const SerialNumGenerate = () => {
const [messageApi, contextHolder] = message.useMessage();
const [form] = Form.useForm();
const [searchForm] = Form.useForm();
// 国家/省份
const [allCountries, setAllCountries] = useState([]);
const [provinces, setProvinces] = useState([]);
// 二维码生成
const [qrUrl, setQrUrl] = useState('');
const [serialNumber, setSerialNumber] = useState('');
const [qrJson, setQrJson] = useState('');
const [loading, setLoading] = useState(false);
// 查询
const [queryLoading, setQueryLoading] = useState(false);
// 弹窗
const [manageVisible, setManageVisible] = useState(false);
const [addModalVisible, setAddModalVisible] = useState(false);
// 业务数据
const [types, setTypes] = useState([]);
const [models, setModels] = useState([]);
const [configs, setConfigs] = useState([]);
// 二维码列表
const [codeList, setCodeList] = useState([]);
const [codeLoading, setCodeLoading] = useState(false);
const [currentPage, setCurrentPage] = useState(1);
const [pageSize] = useState(10);
const [total, setTotal] = useState(0);
// 多选删除
const [selectedRowKeys, setSelectedRowKeys] = useState([]);
// 查看二维码弹窗
const [viewModal, setViewModal] = useState(false);
const [viewRecord, setViewRecord] = useState(null);
// 映射
const countryNameMap = useRef({});
const provinceNameMap = useRef({});
// 工具方法:解析 qrJson
const parseQrJson = (qrJson) => {
if (!qrJson) return {};
try {
return JSON.parse(qrJson);
} catch {
return {};
}
};
// 初始化
useEffect(() => {
const countries = Country.getAllCountries();
setAllCountries(countries || []);
countries.forEach(item => {
countryNameMap.current[item.isoCode] = item.name;
});
loadTypeList();
loadModelList();
loadConfigList();
loadCodeList();
}, [currentPage]);
// 国家切换
const handleCountryChange = (countryCode) => {
const states = State.getStatesOfCountry(countryCode);
setProvinces(states || []);
form.setFieldsValue({ province: undefined });
};
// 加载二维码列表
const loadCodeList = async () => {
setCodeLoading(true);
try {
const params = searchForm.getFieldsValue();
const res = await getCodeListPageApi({ ...params, current: currentPage, size: pageSize });
if (res?.code === 200) {
const rows = res.data.records || res.data || [];
setCodeList(rows);
setTotal(res.data.total || rows.length);
setSelectedRowKeys([]);
}
} catch (e) {
} finally {
setCodeLoading(false);
}
};
// 删除
const handleDelete = async (id) => {
try {
await delteCodesApi(id);
messageApi.success('删除成功');
loadCodeList();
} catch (e) {
messageApi.error('删除失败');
}
};
// 批量删除
const handleBatchDelete = async () => {
if (selectedRowKeys.length === 0) {
message.warning('请选择要删除的数据');
return;
}
try {
await delteCodesApi(selectedRowKeys.join(','));
messageApi.success('批量删除成功');
loadCodeList();
} catch (e) {
messageApi.error('批量删除失败');
}
};
// 查看
const handleView = (record) => {
setViewRecord(record);
setViewModal(true);
};
// 加载数据
const loadTypeList = async () => {
try {
const res = await getRobotTypeListApi({});
if (res?.code === 200) setTypes(res.data || []);
} catch (e) { }
};
const loadModelList = async () => {
try {
const res = await getRobotModelPageApi({ pageNum: 1, pageSize: 100 });
if (res?.code === 200) setModels(res.data || []);
} catch (e) { }
};
const loadConfigList = async () => {
try {
const res = await getRobotConfigListApi({});
if (res?.code === 200) setConfigs(res.data || []);
} catch (e) { }
};
// 生成序列号
const generateSerialSuffix = () => {
const num = Math.floor(Math.random() * 100000000).toString(16).toUpperCase().padStart(8, '0');
const check = Math.floor(Math.random() * 256).toString(16).toUpperCase().padStart(2, '0');
return `${num}-${check}`;
};
// 生成二维码
const generateQRCode = async () => {
try {
const values = await form.validateFields();
console.log(values, "jnjn")
const { model, config, type, country, province } = values;
const ts = Date.now();
const suffix = generateSerialSuffix();
const parts = [];
if (model) parts.push(model + config);
if (country) parts.push(country);
if (province) parts.push(province);
parts.push(ts);
parts.push(suffix);
const serialNumber = parts.join('-');
const qrData = {
model,
config,
type,
countryCode: country,
countryFullName: countryNameMap.current[country] || country,
provinceCode: province,
provinceFullName: provinceNameMap.current[province] || province,
serialNumber
};
const qrContent = JSON.stringify(qrData, null, 2);
const url = await QRCode.toDataURL(qrContent);
setSerialNumber(serialNumber);
setQrJson(qrContent);
setQrUrl(url);
} catch (err) {
console.error(err)
}
};
// 下载
const downloadQRCode = () => {
if (!qrUrl) return messageApi.warning('请先生成');
const link = document.createElement('a');
link.download = `${serialNumber || 'qrcode'}.png`;
link.href = qrUrl;
link.click();
};
// 保存
const saveToDatabase = async () => {
if (!serialNumber) return messageApi.warning('请先生成');
try {
setLoading(true);
const values = form.getFieldsValue();
console.log(values, "oiii", types)
const model = models.find(m => m.displayName === values.model);
const config = configs.find(c => c.displayName === values.config);
const type = types.find(t => t.storeValue === values.type);
const data = {
serialNumber,
modelId: model?.id || 0,
configId: config?.id || 0,
typeId: type?.id || 0,
qrCode: qrUrl,
qrJson: qrJson
};
const res = await saveCodeApi(data);
if (res?.code === 200) {
messageApi.success('保存成功');
loadCodeList();
setAddModalVisible(false);
form.resetFields();
setQrUrl('');
setSerialNumber('');
setQrJson('');
} else {
messageApi.error('保存失败:' + res?.msg);
}
} catch (e) {
messageApi.error('保存失败');
} finally {
setLoading(false);
}
};
// 查询
const handleQueryQRCode = async () => {
// 从搜索表单中获取序列号
const serialNumber = searchForm.getFieldValue('serialNumber');
if (!serialNumber) {
loadCodeList();
return;
}
setQueryLoading(true);
try {
const res = await getCodeImgApi(serialNumber);
if (res.data) {
setCodeList([res.data]);
} else {
messageApi.warning('未查询到数据');
}
} catch (e) {
messageApi.error('查询失败');
} finally {
setQueryLoading(false);
}
};
// 类型/型号/配置
const handleAddType = async (values) => {
return await addRobotTypeApi({ storeValue: values.storeValue, displayName: values.displayName, remark: values.remark || '' });
};
const handleUpdateType = async (values) => {
return await updateRobotTypeApi({ id: values.id, storeValue: values.storeValue, displayName: values.displayName, remark: values.remark });
};
const handleAddModel = async (values) => {
return await addRobotModelApi({ modelName: values.displayName, storeValue: values.storeValue, displayName: values.displayName });
};
const handleUpdateModel = async (values) => {
return await updateRobotModelApi({ id: values.id, modelName: values.displayName, storeValue: values.storeValue, displayName: values.displayName });
};
const handleAddConfig = async (values) => {
return await addRobotConfigApi({ configName: values.displayName, storeValue: values.storeValue, displayName: values.displayName });
};
const handleUpdateConfig = async (values) => {
return await updateRobotConfigApi({ id: values.id, configName: values.displayName, storeValue: values.storeValue, displayName: values.displayName });
};
// 表格列
// 表格列 —— 已修改:全部显示名称,不显示编码
const columns = [
{
title: '序号',
key: 'idx',
width: 70,
render: (_, __, index) => (currentPage - 1) * pageSize + index + 1
},
{ title: '序列号', width: 380, dataIndex: 'serialNumber', key: 'sn', ellipsis: true },
{
title: '型号',
key: 'model',
render: (_, r) => {
const qrInfo = parseQrJson(r.qrJson);
const modelItem = models.find(m => m.storeValue == qrInfo.model);
return modelItem?.displayName || qrInfo.model || '-';
}
},
{
title: '配置',
key: 'config',
render: (_, r) => {
const qrInfo = parseQrJson(r.qrJson);
const configItem = configs.find(c => c.storeValue === qrInfo.config);
return configItem?.displayName || qrInfo.config || '-';
}
},
{
title: '类型',
key: 'type',
render: (_, r) => {
const qrInfo = parseQrJson(r.qrJson);
console.log(types, qrInfo.type)
const typeItem = types.find(t => t.storeValue === qrInfo.type);
return typeItem?.displayName || qrInfo.type || '-';
}
},
{
title: '国家',
key: 'country',
render: (_, r) => parseQrJson(r.qrJson).countryFullName || '-'
},
{
title: '省份',
key: 'province',
render: (_, r) => parseQrJson(r.qrJson).provinceFullName || '-'
},
{
title: '二维码',
key: 'img',
width: 100,
render: (_, r) => r.qrCodeBase64 &&
},
{
title: '操作',
key: 'opt',
width: 180,
fixed: "right",
render: (_, r) => (