datatables data bind json

博客可能围绕Vue.js和HTML5技术,探讨如何对JSON数据进行处理。Vue.js作为前端框架,HTML5是网页标准,JSON是常用数据格式,三者结合可实现高效的数据交互与展示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

/** * 生产消耗管理页面 * 根据代码规范,所有数据交互都通过 DataManager 进行 */ class ShengchanXiaohaoManager { constructor(dataManager) { this.dataManager = dataManager; this.currentUser = null; this.consumptionRecords = []; this.init(); } async init() { try { // 检查用户权限 await this.checkUserPermission(); // 注册数据管理器回调 this.registerDataCallbacks(); // 初始化页面数据 await this.initPageData(); // 绑定事件 this.bindEvents(); console.log('生产消耗管理页面初始化完成'); } catch (error) { console.error('初始化失败:', error); alert('页面初始化失败,请刷新重试'); } } async checkUserPermission() { try { // 通过 DataManager 获取当前用户信息 this.currentUser = await this.dataManager.getCurrentUser(); if (!this.currentUser || this.currentUser.role < 2) { alert('权限不足,无法访问此页面'); window.location.href = '../index.html'; return; } } catch (error) { console.error('权限检查失败:', error); window.location.href = '../index.html'; } } /** * 注册数据管理器回调 */ registerDataCallbacks() { // 注册生产消耗相关回调 this.dataManager.registerCallback('shengchan_xiaohao', (operation, data) => { if (operation === 'add') { this.onConsumptionAdded(data); } else if (operation === 'add_error') { this.onConsumptionError(data); } }); // 注册数据刷新回调 this.dataManager.registerCallback('all', (operation, entity, data) => { if (operation === 'refresh') { this.refreshConsumptionData(); } }); } /** * 初始化页面数据 */ async initPageData() { try { // 确保数据已加载 await this.dataManager.fetchAll(); // 刷新消耗数据 this.refreshConsumptionData(); // 加载统计信息 this.loadStatistics(); // 初始化下拉框数据 this.initSelectOptions(); } catch (error) { console.error('初始化页面数据失败:', error); } } /** * 刷新消耗数据 */ refreshConsumptionData() { // 从 DataManager 获取生产消耗记录 this.consumptionRecords = this.dataManager.getShengchanXiaohaoRecords(); // 更新表格显示 this.updateConsumptionTable(); } /** * 更新消耗表格 */ updateConsumptionTable() { const tableBody = document.getElementById('productionRecordsTable'); if (!tableBody) return; if (this.consumptionRecords.length === 0) { tableBody.innerHTML = '<tr><td colspan="9" class="text-center text-muted">暂无生产记录</td></tr>'; return; } const rows = this.consumptionRecords.map(record => { const dingdanBancai = record.dingdan_bancai || {}; const dingdan = dingdanBancai.dingdan || {}; const chanpin = dingdanBancai.chanpin || {}; const zujian = dingdanBancai.zujian || {}; const bancai = dingdanBancai.bancai || {}; const user = record.user || {}; return ` <tr> <td>${new Date(record.date).toLocaleString('zh-CN')}</td> <td>${dingdan.number || '未指定'}</td> <td>${chanpin.bianhao || '未指定'}</td> <td>${zujian.name || '未指定'}</td> <td><span class="badge badge-primary">${Math.abs(record.shuliang)}</span></td> <td>${this.getBancaiName(bancai)}</td> <td>${user.name || '未知'}</td> <td><span class="badge badge-success">正常</span></td> <td> <button class="btn btn-sm btn-info" onclick="shengchanXiaohaoManager.viewRecord(${record.id})" title="查看详情"> <i class="bi bi-eye"></i> </button> </td> </tr> `; }).join(''); tableBody.innerHTML = rows; } /** * 获取板材名称 */ getBancaiName(bancai) { if (!bancai) return '未知板材'; const caizhi = bancai.caizhi || {}; const mupi1 = bancai.mupi1 || {}; const mupi2 = bancai.mupi2 || {}; return `${caizhi.name || ''}${bancai.houdu || ''}mm ${mupi1.name || ''}/${mupi2.name || ''}`; } /** * 初始化下拉框选项 */ initSelectOptions() { // 初始化订单下拉框 this.updateDingdanSelect(); // 绑定订单变化事件 const dingdanSelect = document.getElementById('dingdanSelect'); if (dingdanSelect) { dingdanSelect.addEventListener('change', () => { this.onDingdanChange(); }); } // 绑定产品变化事件 const chanpinSelect = document.getElementById('chanpinSelect'); if (chanpinSelect) { chanpinSelect.addEventListener('change', () => { this.onChanpinChange(); }); } // 绑定组件变化事件 const zujianSelect = document.getElementById('zujianSelect'); if (zujianSelect) { zujianSelect.addEventListener('change', () => { this.onZujianChange(); }); } } /** * 更新订单下拉框 */ updateDingdanSelect() { const select = document.getElementById('dingdanSelect'); if (!select) return; const dingdans = this.dataManager.getDingdans(); select.innerHTML = '<option value="">请选择订单</option>'; dingdans.forEach(dingdan => { if (!dingdan.deleted) { const option = document.createElement('option'); option.value = dingdan.id; option.textContent = dingdan.number; select.appendChild(option); } }); } /** * 订单变化处理 */ onDingdanChange() { const dingdanSelect = document.getElementById('dingdanSelect'); const chanpinSelect = document.getElementById('chanpinSelect'); const zujianSelect = document.getElementById('zujianSelect'); const productionQuantity = document.getElementById('productionQuantity'); if (!dingdanSelect.value) { chanpinSelect.disabled = true; zujianSelect.disabled = true; productionQuantity.disabled = true; return; } // 更新产品下拉框 const chanpins = this.dataManager.getChanpinsForDingdan(dingdanSelect.value); chanpinSelect.innerHTML = '<option value="">请选择产品</option>'; chanpins.forEach(chanpin => { const option = document.createElement('option'); option.value = chanpin.id; option.textContent = chanpin.bianhao; chanpinSelect.appendChild(option); }); chanpinSelect.disabled = false; zujianSelect.disabled = true; productionQuantity.disabled = true; } /** * 产品变化处理 */ onChanpinChange() { const chanpinSelect = document.getElementById('chanpinSelect'); const zujianSelect = document.getElementById('zujianSelect'); const productionQuantity = document.getElementById('productionQuantity'); if (!chanpinSelect.value) { zujianSelect.disabled = true; productionQuantity.disabled = true; return; } // 更新组件下拉框 const zujians = this.dataManager.getZujiansForChanpin(chanpinSelect.value); zujianSelect.innerHTML = '<option value="">请选择组件</option>'; zujians.forEach(zujian => { const option = document.createElement('option'); option.value = zujian.id; option.textContent = zujian.name; zujianSelect.appendChild(option); }); zujianSelect.disabled = false; productionQuantity.disabled = true; } /** * 组件变化处理 */ onZujianChange() { const zujianSelect = document.getElementById('zujianSelect'); const productionQuantity = document.getElementById('productionQuantity'); if (!zujianSelect.value) { productionQuantity.disabled = true; return; } productionQuantity.disabled = false; // 启用计算按钮 const calculateBtn = document.getElementById('calculateConsumption'); if (calculateBtn) { calculateBtn.disabled = false; } } columns: [ { data: 'id', title: 'ID', width: '60px' }, { data: null, title: '订单信息', render: function(data, type, row) { let html = ''; if (row.dingdan_name) { html += `<div><strong>订单:</strong> ${row.dingdan_name}</div>`; } if (row.chanpin_name) { html += `<div><strong>产品:</strong> ${row.chanpin_name}</div>`; } if (row.zujian_name) { html += `<div><strong>组件:</strong> ${row.zujian_name}</div>`; } return html || '未指定'; } }, { data: 'bancai_name', title: '板材', render: function(data, type, row) { return data || '未知板材'; } }, { data: 'shengchan_shuliang', title: '生产数量', className: 'text-center', render: function(data, type, row) { return `<span class="badge badge-primary">${data || 0}</span>`; } }, { data: 'xiaohao_shuliang', title: '消耗数量', className: 'text-center', render: function(data, type, row) { return `<span class="badge badge-warning">${data || 0}</span>`; } }, { data: 'shijian', title: '时间', render: function(data, type, row) { if (data) { const date = new Date(data); return date.toLocaleString('zh-CN'); } return ''; } }, { data: 'caozuoyuan_name', title: '操作员', render: function(data, type, row) { return data || '未知'; } }, { data: 'zhuangtai', title: '状态', className: 'text-center', render: function(data, type, row) { const statusClass = data === '正常' ? 'success' : 'secondary'; return `<span class="badge badge-${statusClass}">${data || '正常'}</span>`; } }, { data: null, title: '操作', orderable: false, className: 'text-center', width: '120px', render: function(data, type, row) { return ` <button class="btn btn-sm btn-info view-btn" data-id="${row.id}" title="查看详情"> <i class="fas fa-eye"></i> </button> <button class="btn btn-sm btn-primary edit-btn" data-id="${row.id}" title="编辑"> <i class="fas fa-edit"></i> </button> <button class="btn btn-sm btn-danger delete-btn" data-id="${row.id}" title="删除"> <i class="fas fa-trash"></i> </button> `; } } ], order: [[0, 'desc']], pageLength: 25, responsive: true, language: { url: '//cdn.datatables.net/plug-ins/1.10.24/i18n/Chinese.json' }, dom: '<"row"<"col-sm-12 col-md-6"l><"col-sm-12 col-md-6"f>>' + '<"row"<"col-sm-12"tr>>' + '<"row"<"col-sm-12 col-md-5"i><"col-sm-12 col-md-7"p>>', drawCallback: (settings) => { // 重新绑定按钮事件 $('.view-btn').off('click').on('click', (e) => { const id = $(e.currentTarget).data('id'); this.viewRecord(id); }); $('.edit-btn').off('click').on('click', (e) => { const id = $(e.currentTarget).data('id'); this.editRecord(id); }); $('.delete-btn').off('click').on('click', (e) => { const id = $(e.currentTarget).data('id'); this.deleteRecord(id); }); } }); } bindEvents() { // 计算消耗按钮 const calculateBtn = document.getElementById('calculateConsumption'); if (calculateBtn) { calculateBtn.addEventListener('click', () => { this.calculateConsumption(); }); } // 确认生产按钮 const confirmBtn = document.getElementById('confirmProduction'); if (confirmBtn) { confirmBtn.addEventListener('click', () => { this.confirmProduction(); }); } // 刷新按钮 const refreshBtn = document.getElementById('refreshBtn'); if (refreshBtn) { refreshBtn.addEventListener('click', () => { this.refreshData(); }); } // 新增订单按钮 const addDingdanBtn = document.getElementById('addDingdanBtn'); if (addDingdanBtn) { addDingdanBtn.addEventListener('click', () => { this.showAddDingdanModal(); }); } // 添加产品按钮 const addChanpinBtn = document.getElementById('addChanpinBtn'); if (addChanpinBtn) { addChanpinBtn.addEventListener('click', () => { this.showAddChanpinModal(); }); } // 添加组件按钮 const addZujianBtn = document.getElementById('addZujianBtn'); if (addZujianBtn) { addZujianBtn.addEventListener('click', () => { this.showAddZujianModal(); }); } } /** * 计算消耗 */ async calculateConsumption() { try { const dingdanId = document.getElementById('dingdanSelect').value; const chanpinId = document.getElementById('chanpinSelect').value; const zujianId = document.getElementById('zujianSelect').value; const shengchanShuliang = parseInt(document.getElementById('productionQuantity').value); if (!dingdanId || !chanpinId || !zujianId || !shengchanShuliang) { alert('请完整填写生产信息'); return; } // 获取组件的板材消耗信息 const bancais = this.dataManager.getBancaisForZujian(zujianId); const consumptionDetails = document.getElementById('consumptionDetails'); const consumptionList = document.getElementById('consumptionList'); if (bancais.length === 0) { alert('该组件没有配置板材信息'); return; } // 显示消耗明细 consumptionDetails.style.display = 'block'; consumptionList.innerHTML = ''; bancais.forEach(bancai => { // 从 chanpin_zujians 中获取消耗比例 const chanpinZujian = this.dataManager.data.chanpin_zujians.find(cz => cz.chanpin?.id == chanpinId && cz.zujian?.id == zujianId && cz.bancai?.id == bancai.id ); const oneHowMany = chanpinZujian ? chanpinZujian.one_howmany : 1; const xiaohaoShuliang = Math.ceil(shengchanShuliang * oneHowMany); const itemHtml = ` <div class="consumption-item" data-bancai-id="${bancai.id}" data-xiaohao="${xiaohaoShuliang}"> <div class="row"> <div class="col-md-6"> <strong>板材:</strong> ${this.getBancaiName(bancai)} </div> <div class="col-md-3"> <strong>单位消耗:</strong> ${oneHowMany} </div> <div class="col-md-3"> <strong>总消耗:</strong> <span class="text-danger">${xiaohaoShuliang} 张</span> </div> </div> </div> `; consumptionList.innerHTML += itemHtml; }); // 启用确认生产按钮 const confirmBtn = document.getElementById('confirmProduction'); if (confirmBtn) { confirmBtn.disabled = false; } } catch (error) { console.error('计算消耗失败:', error); alert('计算消耗失败,请重试'); } } /** * 确认生产 */ async confirmProduction() { try { const dingdanId = document.getElementById('dingdanSelect').value; const chanpinId = document.getElementById('chanpinSelect').value; const zujianId = document.getElementById('zujianSelect').value; const shengchanShuliang = parseInt(document.getElementById('productionQuantity').value); const consumptionItems = document.querySelectorAll('.consumption-item'); if (consumptionItems.length === 0) { alert('请先计算消耗'); return; } if (!confirm('确认执行生产消耗操作?此操作将扣减库存。')) { return; } // 处理每个板材的消耗 for (const item of consumptionItems) { const bancaiId = parseInt(item.dataset.bancaiId); const xiaohaoShuliang = parseInt(item.dataset.xiaohao); const consumptionData = { dingdan: { id: parseInt(dingdanId) }, chanpin: { id: parseInt(chanpinId) }, zujian: { id: parseInt(zujianId) }, bancai: { id: bancaiId }, shengchan_shuliang: shengchanShuliang, xiaohao_shuliang: xiaohaoShuliang, caozuoyuan: { id: this.currentUser.id }, shijian: new Date().toISOString(), beizhu: `生产${shengchanShuliang}个${document.getElementById('chanpinSelect').selectedOptions[0].text}` }; // 通过 DataManager 处理生产消耗事务 await this.dataManager.processShengchanXiaohao(consumptionData); } alert('生产消耗处理完成'); this.resetForm(); } catch (error) { console.error('确认生产失败:', error); alert('生产消耗处理失败: ' + error.message); } } /** * 重置表单 */ resetForm() { document.getElementById('dingdanSelect').value = ''; document.getElementById('chanpinSelect').innerHTML = '<option value="">请选择产品</option>'; document.getElementById('zujianSelect').innerHTML = '<option value="">请选择组件</option>'; document.getElementById('productionQuantity').value = ''; document.getElementById('chanpinSelect').disabled = true; document.getElementById('zujianSelect').disabled = true; document.getElementById('productionQuantity').disabled = true; document.getElementById('calculateConsumption').disabled = true; document.getElementById('confirmProduction').disabled = true; document.getElementById('consumptionDetails').style.display = 'none'; } /** * 显示添加订单弹窗 */ showAddDingdanModal() { if (window.CustomFormModal) { window.CustomFormModal.show('dingdan', { title: '添加订单', onSuccess: () => { this.refreshData(); } }); } } /** * 显示添加产品弹窗 */ showAddChanpinModal() { const dingdanId = document.getElementById('dingdanSelect').value; if (!dingdanId) { alert('请先选择订单'); return; } if (window.CustomFormModal) { window.CustomFormModal.show('chanpin', { title: '添加产品', onSuccess: () => { this.refreshData(); this.onDingdanChange(); // 刷新产品列表 } }); } } /** * 显示添加组件弹窗 */ showAddZujianModal() { const chanpinId = document.getElementById('chanpinSelect').value; if (!chanpinId) { alert('请先选择产品'); return; } if (window.CustomFormModal) { window.CustomFormModal.show('zujian', { title: '添加组件', onSuccess: () => { this.refreshData(); this.onChanpinChange(); // 刷新组件列表 } }); } } /** * 查看记录详情 */ viewRecord(recordId) { const record = this.consumptionRecords.find(r => r.id === recordId); if (!record) { alert('记录不存在'); return; } const dingdanBancai = record.dingdan_bancai || {}; const dingdan = dingdanBancai.dingdan || {}; const chanpin = dingdanBancai.chanpin || {}; const zujian = dingdanBancai.zujian || {}; const bancai = dingdanBancai.bancai || {}; const user = record.user || {}; const content = ` <div class="row"> <div class="col-md-6"> <p><strong>记录ID:</strong> ${record.id}</p> <p><strong>订单:</strong> ${dingdan.number || '未指定'}</p> <p><strong>产品:</strong> ${chanpin.bianhao || '未指定'}</p> <p><strong>组件:</strong> ${zujian.name || '未指定'}</p> <p><strong>板材:</strong> ${this.getBancaiName(bancai)}</p> </div> <div class="col-md-6"> <p><strong>消耗数量:</strong> ${Math.abs(record.shuliang)} 张</p> <p><strong>消耗时间:</strong> ${new Date(record.date).toLocaleString('zh-CN')}</p> <p><strong>操作员:</strong> ${user.name || '未知'}</p> <p><strong>操作类型:</strong> 生产消耗</p> <p><strong>备注:</strong> ${record.text || '无'}</p> </div> </div> `; // 显示在模态框中 if (window.CustomFormModal) { const modal = document.createElement('div'); modal.className = 'modal fade'; modal.innerHTML = ` <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">生产消耗记录详情</h5> <button type="button" class="btn-close" data-bs-dismiss="modal"></button> </div> <div class="modal-body">${content}</div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button> </div> </div> </div> `; document.body.appendChild(modal); const bootstrapModal = new bootstrap.Modal(modal); bootstrapModal.show(); modal.addEventListener('hidden.bs.modal', () => { document.body.removeChild(modal); }); } } /** * 刷新数据 */ async refreshData() { try { await this.dataManager.refreshData(); this.loadStatistics(); } catch (error) { console.error('刷新数据失败:', error); } } /** * 加载统计信息 */ loadStatistics() { try { const statistics = this.dataManager.getShengchanStatistics(); const todayConsumption = document.getElementById('todayConsumption'); const monthConsumption = document.getElementById('monthConsumption'); const pendingOrders = document.getElementById('pendingOrders'); const lowStockCount = document.getElementById('lowStockCount'); if (todayConsumption) todayConsumption.textContent = `${statistics.today_consumption} 张`; if (monthConsumption) monthConsumption.textContent = `${statistics.month_consumption} 张`; if (pendingOrders) pendingOrders.textContent = `${statistics.pending_orders} 个`; if (lowStockCount) lowStockCount.textContent = `${statistics.low_stock_count} 种`; } catch (error) { console.error('加载统计信息失败:', error); } } /** * 生产消耗添加成功回调 */ onConsumptionAdded(data) { console.log('生产消耗添加成功:', data); // 数据会通过 DataManager 的回调自动刷新 } /** * 生产消耗添加失败回调 */ onConsumptionError(data) { console.error('生产消耗处理失败:', data); alert('生产消耗处理失败: ' + data.error); } } // 页面加载完成后初始化 document.addEventListener('DOMContentLoaded', async function() { // 检查必要的依赖 if (typeof DataManager === 'undefined') { console.error('DataManager 未加载'); alert('系统组件未加载完成,请刷新页面'); return; } try { // 导入 DataManager const { DataManager } = await import('../data/DataManager.js'); // 创建 DataManager 实例 const dataManager = new DataManager(); await dataManager.fetchAll(); // 初始化生产消耗管理器 window.shengchanXiaohaoManager = new ShengchanXiaohaoManager(dataManager); console.log('生产消耗管理系统初始化完成'); } catch (error) { console.error('系统初始化失败:', error); alert('系统初始化失败,请刷新页面重试'); } }); showAddModal() { if (window.CustomFormModal) { window.CustomFormModal.show('shengchan-xiaohao', { title: '添加生产消耗', onSuccess: () => { this.refreshData(); } }); } else { console.error('CustomFormModal 未加载'); alert('弹窗组件未加载,请刷新页面重试'); } } async viewRecord(id) { try { const response = await fetch(`../php_api/index.php?action=getShengchanXiaohao&id=${id}`); const result = await response.json(); if (result.success && result.data) { const record = result.data; let content = ` <div class="row"> <div class="col-md-6"> <p><strong>ID:</strong> ${record.id}</p> <p><strong>订单:</strong> ${record.dingdan_name || '未指定'}</p> <p><strong>产品:</strong> ${record.chanpin_name || '未指定'}</p> <p><strong>组件:</strong> ${record.zujian_name || '未指定'}</p> <p><strong>板材:</strong> ${record.bancai_name || '未知'}</p> </div> <div class="col-md-6"> <p><strong>生产数量:</strong> ${record.shengchan_shuliang}</p> <p><strong>消耗数量:</strong> ${record.xiaohao_shuliang}</p> <p><strong>时间:</strong> ${new Date(record.shijian).toLocaleString('zh-CN')}</p> <p><strong>操作员:</strong> ${record.caozuoyuan_name || '未知'}</p> <p><strong>状态:</strong> ${record.zhuangtai || '正常'}</p> </div> </div> `; if (record.beizhu) { content += `<div class="row"><div class="col-12"><p><strong>备注:</strong> ${record.beizhu}</p></div></div>`; } $('#viewModalBody').html(content); $('#viewModal').modal('show'); } else { alert('获取记录详情失败'); } } catch (error) { console.error('查看记录失败:', error); alert('查看记录失败,请重试'); } } editRecord(id) { if (window.CustomFormModal) { window.CustomFormModal.show('shengchan-xiaohao', { title: '编辑生产消耗', mode: 'edit', recordId: id, onSuccess: () => { this.refreshData(); } }); } else { console.error('CustomFormModal 未加载'); alert('弹窗组件未加载,请刷新页面重试'); } } async deleteRecord(id) { if (!confirm('确定要删除这条生产消耗记录吗?此操作不可撤销。')) { return; } try { const response = await fetch('../php_api/index.php?action=deleteShengchanXiaohao', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ id: id }) }); const result = await response.json(); if (result.success) { alert('删除成功'); this.refreshData(); } else { alert('删除失败: ' + (result.message || '未知错误')); } } catch (error) { console.error('删除记录失败:', error); alert('删除失败,请重试'); } } refreshData() { if (this.dataTable) { this.dataTable.ajax.reload(); } } // 获取统计信息 async loadStatistics() { try { const response = await fetch('../php_api/index.php?action=getShengchanXiaohaoStatistics'); const result = await response.json(); if (result.success && result.data) { const stats = result.data; $('#totalRecords').text(stats.total_records || 0); $('#todayRecords').text(stats.today_records || 0); $('#totalConsumption').text(stats.total_consumption || 0); $('#todayConsumption').text(stats.today_consumption || 0); } } catch (error) { console.error('获取统计信息失败:', error); } } } // 页面加载完成后初始化 $(document).ready(function() { // 检查必要的依赖 if (typeof $ === 'undefined') { console.error('jQuery 未加载'); return; } if (typeof $.fn.DataTable === 'undefined') { console.error('DataTables 未加载'); return; } // 初始化管理器 window.shengchanXiaohaoManager = new ShengchanXiaohaoManager(); // 加载统计信息 window.shengchanXiaohaoManager.loadStatistics(); });------------语法错误
最新发布
08-11
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Farmwang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值