Browse Source

first commit

liuhairui 4 months ago
parent
commit
a208fe3e0e

File diff suppressed because it is too large
+ 1332 - 261
application/admin/controller/Deliver.php


+ 62 - 31
application/admin/controller/Finishedproduct.php

@@ -39,53 +39,63 @@ class Finishedproduct extends Backend
         // 获取工单编号列表
         $db3 = Db::connect(config('database.db3'));
         $gdRows = $db3->query("SELECT DISTINCT `Gd_gdbh`, `Gd_客户代号`, `Gd_cpdh` FROM `工单_基本资料` WHERE `Gd_客户代号` = ?", ['J0031']);
+
         $Gd_gdbhList = array_column($gdRows, 'Gd_gdbh');
         $gdbhList = array_column($gdRows, 'Gd_cpdh');
         if (empty($gdbhList)) {
             $this->assign([
                 'data' => '',
-                'total' =>'',
+                'total' => '',
             ]);
         }
 
         // Mongo 查询
         $mongo = \think\Db::connect('mongodb');
-        $where = ['jjcp_cpdh' => ['in', $gdbhList],'jjcp_gdbh' => ['in', $Gd_gdbhList], 'jjcp_smb' => '末 板'];
+        $where = ['成品编码' => ['in', $gdbhList],'jjcp_gdbh' => ['in', $Gd_gdbhList], 'jjcp_smb' => '末 板'];
+        // $where = ['成品编码' => ['in', $gdbhList], 'jjcp_smb' => '末 板'];
         if (!empty($params['search'])) {
             $where['成品编码|成品名称|jjcp_gdbh|订单编号'] = new \MongoDB\BSON\Regex($params['search'], 'i');
         }
 
-        // 1. 查询所有符合条件的成品数据(不分页)
-        $all_products = $mongo->name('finished_products')
+        // 查询符合条件的成品数据
+        $al_products = $mongo->name('finished_products')
             ->where($where)
-            ->order('UniqId', 'desc')
+            ->order('Sys_rq', 'desc')
+            ->select();
+
+        // 查询 texts = 新增产品 的数据
+        $xz_products = $mongo->name('finished_products')
+            ->where('texts', '新增产品')
+            ->order('Sys_rq', 'desc')
             ->select();
 
-        // 2. 按订单编号 + 工单编号分组聚合,并处理多个cpdh与成品编码
+        // 合并数据
+        $all_products = array_merge($al_products, $xz_products);
+
+        // 分组聚合处理
         $grouped_products = [];
         foreach ($all_products as $item) {
-
-            $originDateStr = $item['Sys_rq']; // 例如:'20/6/2025 16:01:43'
-            $dt = \DateTime::createFromFormat('d/m/Y H:i:s', $originDateStr);
-            $standardDate = $dt ? $dt->format('Y-m-d H:i:s') : null;
+            // 转换日期格式(如果是 d/m/Y H:i:s)
+            $date = \DateTime::createFromFormat('d/m/Y H:i:s', $item['Sys_rq']);
+            $item['Sys_rq'] = $date ? $date->format('Y-m-d H:i:s') : $item['Sys_rq'];
 
             $group_key = $item['订单编号'] . '_' . $item['jjcp_gdbh'];
 
             if (!isset($grouped_products[$group_key])) {
                 $grouped_products[$group_key] = [
+                    'Sys_rq' => $item['Sys_rq'],
                     'order_ddbh' => $item['订单编号'],
                     'gdbh' => $item['jjcp_gdbh'],
                     'cpbm' => $item['成品编码'],
                     'cpmc' => $item['成品名称'],
-                    'Sys_rq' => $standardDate,
-                    'sl' => 0, // 库存总数
+                    'sl' => 0,
                     'cpdh_list' => [],
                     'cpbm_list' => []
                 ];
             }
-            $grouped_products[$group_key]['sl'] += (int)$item['jjcp_sl']; // 累计库存数量
 
-            // 收集不同的cpdh和cpbm(成品编码)
+            $grouped_products[$group_key]['sl'] += (int)$item['jjcp_sl'];
+
             if (!in_array($item['jjcp_cpdh'], $grouped_products[$group_key]['cpdh_list'])) {
                 $grouped_products[$group_key]['cpdh_list'][] = $item['jjcp_cpdh'];
             }
@@ -95,19 +105,26 @@ class Finishedproduct extends Backend
             }
         }
 
-        // 格式化成用逗号连接的字符串
+        // 格式化列表字符串
         foreach ($grouped_products as &$group) {
             $group['cpdh'] = implode(',', $group['cpdh_list']);
             $group['cpbm'] = implode(',', $group['cpbm_list']);
-            unset($group['cpdh_list'], $group['cpbm_list']); // 清理临时字段
+            unset($group['cpdh_list'], $group['cpbm_list']);
         }
 
-        // 3. 将聚合后结果分页(稳定分页
+        // 聚合结果排序(按时间降序
         $all_grouped = array_values($grouped_products);
+        usort($all_grouped, function ($a, $b) {
+            $timeA = strtotime($a['Sys_rq']) ?: 0;
+            $timeB = strtotime($b['Sys_rq']) ?: 0;
+            return $timeB <=> $timeA;
+        });
+
+        // 再分页
         $total = count($all_grouped);
         $paged_grouped = array_slice($all_grouped, $offset, $limit);
 
-        // 4. 获取库存出货数据并计算剩余数
+        // 查询库存并计算剩余数
         foreach ($paged_grouped as &$prod) {
             $inventory = $mongo->name('inventory_summary')->where([
                 'order_ddbh' => $prod['order_ddbh'],
@@ -115,15 +132,14 @@ class Finishedproduct extends Backend
                 'cpmc' => $prod['cpmc'],
             ])->find();
 
-            // 出货数量(若无数据则为 0)
             $total_chu_quantity = isset($inventory['total_chu_quantity']) ? (int)$inventory['total_chu_quantity'] : 0;
             $prod['total_chu_quantity'] = $total_chu_quantity;
-
-            // 计算剩余数 = sl - 出货数
             $prod['remaining_quantity'] = $prod['sl'] - $total_chu_quantity;
         }
         unset($prod);
 
+
+
         if (request()->isAjax()) {
             return json([
                 'code'  => 1,
@@ -216,25 +232,40 @@ class Finishedproduct extends Backend
 
         foreach ($data['data'] as $item) {
             $insertList[] = [
-                '成品名称' => $item['jjcp_cpmc'],
-                '成品编码' => $item['jjcp_cpbm'],
+                'jjcp_num'  => '',
+                'jjcp_yjno'  => '',
+                'jjcp_cpmc'  => '',
+                '客户料号'  => '',
+                '仓库编号'  => '',
+                '仓库名称'  => '',
+                'jjcp_desc'  => $item['remark'],
+                '入仓类型'  => '',
+                '机型备注'  => '',
+                'Sys_id'  => '',
+                'UniqId'  => '',
+
+                '成品名称' => $item['cpmc'],
+                'jjcp_cpdh' => $item['cpbm'],
+                '成品编码' => $item['cpbm'],
                 '订单编号' => $item['order_ddbh'],
-                'jjcp_gdbh' => $item['jjcp_gdbh'],
-                'jjcp_sl'   => intval($item['jjcp_sl']),
+                'jjcp_gdbh' => $item['gdbh'],
+                'jjcp_sl'   => intval($item['sl']),
                 'jjcp_smb'  => '末 板',
+                'jjcp_dw'  => '张',
                 'Mod_rq'  => '',
+                'texts'  => '新增产品',
                 'company'  => $userinfo['company'],
                 'jjcp_sj' => date('Y-m-d H:i:s'),
                 'Sys_rq' => date('Y-m-d H:i:s')
             ];
         }
 
-        try {
-            $mongo->name('Finished_products')->insertAll($insertList);
-            return json(['status' => 'success', 'msg' => '成功插入 MongoDB']);
-        } catch (\Exception $e) {
-            return json(['status' => 'error', 'msg' => '插入失败:' . $e->getMessage()]);
-        }
+//        try {
+        $mongo->name('Finished_products')->insertAll($insertList);
+        $this->success('成功插入');
+//        } catch (\Exception $e) {
+//            return json(['status' => 'error', 'msg' => '插入失败:' . $e->getMessage()]);
+//        }
     }
 
 

+ 577 - 41
application/admin/controller/QcodeAdd.php

@@ -12,6 +12,7 @@ use app\admin\model\QcodeBach;
 use app\admin\model\QcodeSmall;
 use app\admin\model\QcodeLiushui;
 use fast\Arr;
+use MongoDB\BSON\ObjectId;
 use think\Db;
 use think\Session;
 
@@ -73,47 +74,63 @@ class QcodeAdd extends Backend{
         // 获取工单编号列表
         $db3 = Db::connect(config('database.db3'));
         $gdRows = $db3->query("SELECT DISTINCT `Gd_gdbh`, `Gd_客户代号`, `Gd_cpdh` FROM `工单_基本资料` WHERE `Gd_客户代号` = ?", ['J0031']);
+
         $Gd_gdbhList = array_column($gdRows, 'Gd_gdbh');
         $gdbhList = array_column($gdRows, 'Gd_cpdh');
         if (empty($gdbhList)) {
             $this->assign([
                 'data' => '',
-                'total' =>'',
+                'total' => '',
             ]);
         }
 
         // Mongo 查询
         $mongo = \think\Db::connect('mongodb');
-        $where = ['jjcp_cpdh' => ['in', $gdbhList],'jjcp_gdbh' => ['in', $Gd_gdbhList], 'jjcp_smb' => '末 板'];
+        $where = ['成品编码' => ['in', $gdbhList],'jjcp_gdbh' => ['in', $Gd_gdbhList], 'jjcp_smb' => '末 板'];
+        // $where = ['成品编码' => ['in', $gdbhList], 'jjcp_smb' => '末 板'];
         if (!empty($params['search'])) {
             $where['成品编码|成品名称|jjcp_gdbh|订单编号'] = new \MongoDB\BSON\Regex($params['search'], 'i');
         }
 
-        // 1. 查询所有符合条件的成品数据(不分页)
-        $all_products = $mongo->name('finished_products')
+        // 查询符合条件的成品数据
+        $al_products = $mongo->name('finished_products')
             ->where($where)
-            ->order('UniqId', 'desc')
+            ->order('Sys_rq', 'desc')
+            ->select();
+
+        // 查询 texts = 新增产品 的数据
+        $xz_products = $mongo->name('finished_products')
+            ->where('texts', '新增产品')
+            ->order('Sys_rq', 'desc')
             ->select();
 
-        // 2. 按订单编号 + 工单编号分组聚合,并处理多个cpdh与成品编码
+        // 合并数据
+        $all_products = array_merge($al_products, $xz_products);
+
+        // 分组聚合处理
         $grouped_products = [];
         foreach ($all_products as $item) {
+            // 转换日期格式(如果是 d/m/Y H:i:s)
+            $date = \DateTime::createFromFormat('d/m/Y H:i:s', $item['Sys_rq']);
+            $item['Sys_rq'] = $date ? $date->format('Y-m-d H:i:s') : $item['Sys_rq'];
+
             $group_key = $item['订单编号'] . '_' . $item['jjcp_gdbh'];
 
             if (!isset($grouped_products[$group_key])) {
                 $grouped_products[$group_key] = [
+                    'Sys_rq' => $item['Sys_rq'],
                     'order_ddbh' => $item['订单编号'],
                     'gdbh' => $item['jjcp_gdbh'],
                     'cpbm' => $item['成品编码'],
                     'cpmc' => $item['成品名称'],
-                    'sl' => 0, // 库存总数
+                    'sl' => 0,
                     'cpdh_list' => [],
                     'cpbm_list' => []
                 ];
             }
-            $grouped_products[$group_key]['sl'] += (int)$item['jjcp_sl']; // 累计库存数量
 
-            // 收集不同的cpdh和cpbm(成品编码)
+            $grouped_products[$group_key]['sl'] += (int)$item['jjcp_sl'];
+
             if (!in_array($item['jjcp_cpdh'], $grouped_products[$group_key]['cpdh_list'])) {
                 $grouped_products[$group_key]['cpdh_list'][] = $item['jjcp_cpdh'];
             }
@@ -123,19 +140,26 @@ class QcodeAdd extends Backend{
             }
         }
 
-        // 格式化成用逗号连接的字符串
+        // 格式化列表字符串
         foreach ($grouped_products as &$group) {
             $group['cpdh'] = implode(',', $group['cpdh_list']);
             $group['cpbm'] = implode(',', $group['cpbm_list']);
-            unset($group['cpdh_list'], $group['cpbm_list']); // 清理临时字段
+            unset($group['cpdh_list'], $group['cpbm_list']);
         }
 
-        // 3. 将聚合后结果分页(稳定分页
+        // 聚合结果排序(按时间降序
         $all_grouped = array_values($grouped_products);
+        usort($all_grouped, function ($a, $b) {
+            $timeA = strtotime($a['Sys_rq']) ?: 0;
+            $timeB = strtotime($b['Sys_rq']) ?: 0;
+            return $timeB <=> $timeA;
+        });
+
+        // 再分页
         $total = count($all_grouped);
         $paged_grouped = array_slice($all_grouped, $offset, $limit);
 
-        // 4. 获取库存出货数据并计算剩余数
+        // 查询库存并计算剩余数
         foreach ($paged_grouped as &$prod) {
             $inventory = $mongo->name('inventory_summary')->where([
                 'order_ddbh' => $prod['order_ddbh'],
@@ -143,14 +167,12 @@ class QcodeAdd extends Backend{
                 'cpmc' => $prod['cpmc'],
             ])->find();
 
-            // 出货数量(若无数据则为 0)
             $total_chu_quantity = isset($inventory['total_chu_quantity']) ? (int)$inventory['total_chu_quantity'] : 0;
             $prod['total_chu_quantity'] = $total_chu_quantity;
-
-            // 计算剩余数 = sl - 出货数
             $prod['remaining_quantity'] = $prod['sl'] - $total_chu_quantity;
         }
         unset($prod);
+
         return json([
             'code'  => 1,
             'data'  => $paged_grouped,
@@ -160,6 +182,518 @@ class QcodeAdd extends Backend{
         ]);
     }
 
+
+    public function add_bach()
+    {
+        if (!$this->request->isAjax()) {
+            $this->error('请求错误');
+        }
+
+        $data = input('row');
+        if (empty($data)) {
+            $this->error('参数错误');
+        }
+
+        $data = json_decode($data, true);
+
+        if (json_last_error() !== JSON_ERROR_NONE) {
+            $this->error('JSON解析错误');
+        }
+
+        if (empty($data['products'])) {
+            $this->error('产品数据不能为空');
+        }
+
+        $userinfo = Session::get('admin');
+        if (empty($userinfo) || !isset($userinfo['company'])) {
+            $this->error('用户信息获取失败');
+        }
+
+        $mongo = \think\Db::connect('mongodb');
+        $collection = $userinfo['company'] . '_qcode_bach';
+        $bachsummary = $userinfo['company'] . '_qcode_bachsummary';
+
+        $insertData = [];
+        $currentday = date('Y-m-d');
+        $currentTime = date('Y-m-d H:i:s');
+        $timestamp = time();
+        $bachNum = 'BACH' . date('YmdHis') . mt_rand(1000, 9999);
+
+        $totalQuantity = 0;
+        $totalBoxes = 0;
+        $totalPallets = 0;
+        $palletSequence = 1; // 全局托盘序号计数器
+
+        foreach ($data['products'] as $product) {
+            $small_num = 20;
+            $tray_num = 6;
+            $box_num = 3;
+            $total_boxes = $tray_num * $box_num;
+
+            $remaining_quantity = (int)$product['remaining_quantity'];
+            $larger_num = ceil($remaining_quantity / $small_num);
+            $large_num = ceil($larger_num / $total_boxes);
+
+            $totalQuantity += $remaining_quantity;
+            $totalBoxes += $larger_num;
+            $totalPallets += $large_num;
+
+            // 计算完整托盘数和剩余箱数
+            $full_pallets = floor($larger_num / $total_boxes);
+            $remaining_boxes = $larger_num % $total_boxes;
+
+            // 为每个托盘创建记录
+            for ($i = 1; $i <= $large_num; $i++) {
+                $is_full_pallet = ($i <= $full_pallets) || ($i == $full_pallets + 1 && $remaining_boxes == $total_boxes);
+                $boxes_in_pallet = $is_full_pallet ? $total_boxes : ($i == $full_pallets + 1 ? $remaining_boxes : 0);
+
+                $insertData[] = [
+                    // 用户信息相关字段
+                    'userid' => $userinfo['id'],                 // 用户ID
+                    'supplier_id' => $userinfo['id'],            // 供应商ID (同用户ID)
+                    'supplier_code' => $userinfo['printer_code'], // 供应商编码/打印机编码
+                    'supplier_name' => $data['company_name'],    // 供应商名称/公司名称
+
+                    // 托盘信息相关字段
+                    'pallet' => $palletSequence,                 // 托盘编号 (全局唯一序号)
+                    'pallet_sequence' => $palletSequence,        // 托盘序号 (同pallet字段,冗余设计)
+                    'pallet_type' => $is_full_pallet ? 'full' : 'partial', // 托盘类型: full-整托/partial-部分托
+
+                    // 产品基本信息
+                    'matter_no' => $product['gdbh'],             // 产品编号/工单编号
+                    'matter_id' => $product['gdbh'],             // 产品ID (同工单编号)
+                    'matter_type' => '01',                       // 产品类型 (固定值01)
+                    'order_ddbh' => $product['order_ddbh'],      // 订单编号
+                    'cpbm' => $product['cpbm'],                  // 产品编码
+                    'matter_name' => $product['cpmc'],           // 产品名称
+                    'remark' => $product['remark'],              // 备注信息
+
+                    // 数量单位信息
+                    'num_danwei' => '2',                         // 数量单位类型 (固定值2)
+                    'danwei' => '套',                            // 单位名称 (套)
+
+                    // 数量计算相关字段
+                    'num' => $i <= $full_pallets ? $small_num * $total_boxes : ($i == $full_pallets + 1 ? $small_num * $remaining_boxes : 0), // 本托盘实际产品数量
+                    'small_num' => $small_num,                   // 每箱产品数量 (固定20)
+                    'tray_num' => $tray_num,                     // 每层箱数 (固定6)
+                    'box_num' => $box_num,                       // 每托盘层数 (固定3)
+                    'total_boxes' => $total_boxes,               // 每托盘总箱数 (tray_num * box_num)
+                    'boxes_in_pallet' => $boxes_in_pallet,       // 本托盘实际箱数 (full时为18,partial时为余数)
+
+                    // 托盘汇总信息
+                    'large_num' => $large_num,                   // 本产品总托盘数
+                    'larger_num' => $larger_num,                 // 本产品总箱数
+
+                    // 托盘尺寸规格
+                    'pallet_height' => '1.05',                   // 托盘高度(米)
+                    'pallet_length' => '0.9',                    // 托盘长度(米)
+                    'pallet_width' => '1.2',                     // 托盘宽度(米)
+
+                    // 物流相关字段 (当前为空)
+                    'l_reservation' => '',                       // 物流预留字段
+                    'l_flow' => '1',                             // 物流流向 (固定值1)
+                    'l_weight' => '',                            // 物流重量
+                    's_flow' => '',                              // 备用流向字段
+                    's_weight' => '',                            // 备用重量字段
+                    's_reservation' => '',                       // 备用预留字段
+
+                    // 状态信息
+                    'bach_status' => 0,                          // 批次状态 (0-初始状态)
+                    'bach_ids' => $bachNum,                      // 批次编号 (唯一标识)
+                    'large_endnum' => $large_num,                // 本产品结束托盘号 (同large_num)
+
+                    // 日期相关字段
+                    'manufacture_date' => '',                    // 生产日期 (空)
+                    'print_date' => '',                          // 打印日期 (空)
+                    'sys_rq' => $currentday,                     // 系统日期 (YYYY-MM-DD)
+                    'created_at' => $currentTime,                // 创建时间 (YYYY-MM-DD HH:MM:SS)
+                    'create_time' => $timestamp,                 // 创建时间戳 (Unix timestamp)
+                    'updated_at' => '',                          // 更新时间 (空)
+
+                    // 系统标志字段
+                    'sync_flag' => '0',                          // 同步标志 (0-未同步)
+
+                    // 删除相关字段
+                    'delete_time' => '',                         // 删除时间 (空)
+                    'delect_time' => ''                          // 删除时间 (拼写错误,同delete_time)
+                ];
+
+                $palletSequence++; // 递增全局托盘序号
+            }
+        }
+
+        $insertData_bachsummary = [
+            'bach_ids' => $bachNum,
+            'userid' => $userinfo['id'],
+            'supplier_id' => $userinfo['id'],
+            'supplier_code' => $userinfo['printer_code'],
+            'supplier_name' => $data['company_name'],
+            'total_quantity' => $totalQuantity,
+            'total_boxes' => $totalBoxes,
+            'total_pallets' => $totalPallets,
+            'full_pallets' => $totalPallets - count(array_filter($insertData, function($item) { return $item['pallet_type'] === 'partial'; })),
+            'partial_pallets' => count(array_filter($insertData, function($item) { return $item['pallet_type'] === 'partial'; })),
+            'product_count' => count($data['products']),
+            'bach_status' => 0,
+            'sys_rq' => $currentday,
+            'created_at' => $currentTime,
+            'create_time' => $timestamp,
+            'updated_at' => '',
+            'delete_time' => ''
+        ];
+//echo "<pre>";
+//print_r($insertData);
+//echo "<pre>";die;
+        // 插入数据
+        $mongo->name($collection)->insertAll($insertData);
+        $mongo->name($bachsummary)->insert($insertData_bachsummary);
+//die;
+        // 更新库存信息
+        foreach ($data['products'] as $product) {
+            $where = [
+                'gdbh' => $product['gdbh'],
+                'order_ddbh' => $product['order_ddbh'],
+                'cpmc' => $product['cpmc'],
+            ];
+
+            $actual_quantity = isset($product['actual_quantity']) ? (int)$product['actual_quantity'] : 0;
+            $remaining_quantity = isset($product['remaining_quantity']) ? (int)$product['remaining_quantity'] : 0;
+
+            $insertData = [
+                'gdbh'                => $product['gdbh'],
+                'order_ddbh'          => $product['order_ddbh'],
+                'cpbm'                => $product['cpbm'],
+                'cpmc'                => $product['cpmc'],
+                'total_ru_quantity'   => $remaining_quantity,
+                'total_chu_quantity'  => $actual_quantity,
+                'remaining_quantity'  => $remaining_quantity - $actual_quantity,
+                'created_at'          => date('Y-m-d H:i:s'),
+                'updated_at'          => '',
+                'mod_rq'              => '',
+                'company'             => $data['company_name'] ?? '',
+            ];
+
+            $existing = $mongo->name('inventory_summary')->where($where)->find();
+
+            if ($existing) {
+                $new_chu = (int)$existing['total_chu_quantity'] + $actual_quantity;
+                $new_remaining = (int)$existing['remaining_quantity'] - $actual_quantity;
+
+                $mongo->name('inventory_summary')
+                    ->where($where)
+                    ->update([
+                        'total_ru_quantity'   => (int)$existing['total_ru_quantity'],
+                        'total_chu_quantity' => $new_chu,
+                        'remaining_quantity'  => $new_remaining,
+                        'updated_at'          => date('Y-m-d H:i:s'),
+                    ]);
+            } else {
+                $mongo->name('inventory_summary')->insert($insertData);
+            }
+
+            $mongo->name('inventory_records')->insert($insertData);
+        }
+
+        $this->success('添加成功');
+    }
+//    public function add_bach()
+//    {
+//        if (!$this->request->isAjax()) {
+//            $this->error('请求错误');
+//        }
+//
+//        $data = input('row');
+//        if (empty($data)) {
+//            $this->error('参数错误');
+//        }
+//
+//        $data = json_decode($data, true);
+//
+//        if (json_last_error() !== JSON_ERROR_NONE) {
+//            $this->error('JSON解析错误');
+//        }
+//
+//        if (empty($data['products'])) {
+//            $this->error('产品数据不能为空');
+//        }
+//
+//        $userinfo = Session::get('admin');
+//        if (empty($userinfo) || !isset($userinfo['company'])) {
+//            $this->error('用户信息获取失败');
+//        }
+//
+//        $mongo = \think\Db::connect('mongodb');
+//        $collection = $userinfo['company'] . '_qcode_bach';
+//        $bachsummary = $userinfo['company'] . '_qcode_bachsummary';
+//
+//        $insertData = [];
+//        $currentday = date('Y-m-d');
+//        $currentTime = date('Y-m-d H:i:s');
+//        $timestamp = time();
+//        $bachNum = 'BACH' . date('YmdHis') . mt_rand(1000, 9999);
+//
+//        $totalQuantity = 0;
+//        $totalBoxes = 0;
+//        $totalPallets = 0;
+//
+//        foreach ($data['products'] as $product) {
+//            $small_num = 20;
+//            $tray_num = 6;
+//            $box_num = 3;
+//            $total_boxes = $tray_num * $box_num;
+//
+//            $remaining_quantity = (int)$product['remaining_quantity'];
+//            $larger_num = ceil($remaining_quantity / $small_num);
+//            $large_num = ceil($larger_num / $total_boxes);
+//
+//            $totalQuantity += $remaining_quantity;
+//            $totalBoxes += $larger_num;
+//            $totalPallets += $large_num;
+//
+//            $palletRange = '1-' . $large_num;
+//
+//            $insertData[] = [
+//                'userid' => $userinfo['id'],
+//                'supplier_id' => $userinfo['id'],
+//                'supplier_code' => $userinfo['printer_code'],
+//                'supplier_name' => $data['company_name'],
+//                'pallet' => $palletRange,
+//                'matter_no' => $product['gdbh'],
+//                'matter_id' => $product['gdbh'],
+//                'matter_type' => '01',
+//                'order_ddbh' => $product['order_ddbh'],
+//                'cpbm' => $product['cpbm'],
+//                'matter_name' => $product['cpmc'],
+//                'remark' => $product['remark'],
+//                'num_danwei' => '2',
+//                'danwei' => '套',
+//                'num' => $remaining_quantity,
+//                'small_num' => $small_num,
+//                'tray_num' => $tray_num,
+//                'box_num' => $box_num,
+//                'total_boxes' => $total_boxes,
+//                'large_num' => $large_num,
+//                'larger_num' => $larger_num,
+//                'pallet_height' => '1.05',
+//                'pallet_length' => '0.9',
+//                'pallet_width' => '1.2',
+//                'l_reservation' => '',
+//                'l_flow' => '1',
+//                'l_weight' => '',
+//                's_flow' => '',
+//                's_weight' => '',
+//                's_reservation' => '',
+//                'bach_status' => 0,
+//                'bach_ids' => $bachNum,
+//                'large_endnum' => $large_num,
+//                'manufacture_date' => '',
+//                'print_date' => '',
+//                'sys_rq' => $currentday,
+//                'created_at' => $currentTime,
+//                'create_time' => $timestamp,
+//                'updated_at' => '',
+//                'sync_flag' => '0',
+//                'delete_time' => '',
+//                'delect_time' => ''
+//            ];
+//        }
+//
+//        $insertData_bachsummary = [
+//            'bach_ids' => $bachNum,
+//            'userid' => $userinfo['id'],
+//            'supplier_id' => $userinfo['id'],
+//            'supplier_code' => $userinfo['printer_code'],
+//            'supplier_name' => $data['company_name'],
+//            'total_quantity' => $totalQuantity,
+//            'total_boxes' => $totalBoxes,
+//            'total_pallets' => $totalPallets,
+//            'product_count' => count($data['products']),
+//            'bach_status' => 0,
+//            'sys_rq' => $currentday,
+//            'created_at' => $currentTime,
+//            'create_time' => $timestamp,
+//            'updated_at' => '',
+//            'delete_time' => ''
+//        ];
+//
+//echo "<pre>";
+//print_r($insertData);
+//echo "<pre>";die;
+//            $mongo->name($collection)->insertAll($insertData);
+//            $mongo->name($bachsummary)->insert($insertData_bachsummary);
+//
+//
+//        foreach ($data['products'] as $product) {
+//            $where = [
+//                'gdbh' => $product['gdbh'],
+//                'order_ddbh' => $product['order_ddbh'],
+//                'cpmc' => $product['cpmc'],
+//            ];
+//
+//            // 实际出库数量
+//            $actual_quantity = isset($product['actual_quantity']) ? (int)$product['actual_quantity'] : 0;
+//            $remaining_quantity = isset($product['remaining_quantity']) ? (int)$product['remaining_quantity'] : 0;
+//
+//            // 插入/更新字段
+//            $insertData = [
+//                'gdbh'                => $product['gdbh'],
+//                'order_ddbh'          => $product['order_ddbh'],
+//                'cpbm'                => $product['cpbm'],
+//                'cpmc'                => $product['cpmc'],
+//                'total_ru_quantity'   => $remaining_quantity,            // 入库数来自当前剩余
+//                'total_chu_quantity'  => $actual_quantity,              // 本次出库数
+//                'remaining_quantity'  => $remaining_quantity - $actual_quantity, // 计算结存
+//                'created_at'          => date('Y-m-d H:i:s'),
+//                'updated_at'          => '',
+//                'mod_rq'              => '',
+//                'company'             => $data['company_name'] ?? '',
+//            ];
+//
+//            // 查询是否已存在
+//            $existing = $mongo->name('inventory_summary')->where($where)->find();
+//
+//            if ($existing) {
+//                // 累加更新
+//                $new_chu = (int)$existing['total_chu_quantity'] + $actual_quantity;
+//                $new_remaining = (int)$existing['remaining_quantity'] - $actual_quantity;
+//
+//                $mongo->name('inventory_summary')
+//                    ->where($where)
+//                    ->update([
+//                        'total_ru_quantity'   => (int)$existing['total_ru_quantity'], // 保持不变或你可定义逻辑
+//                        'total_chu_quantity' => $new_chu,
+//                        'remaining_quantity'  => $new_remaining,
+//                        'updated_at'          => date('Y-m-d H:i:s'),
+//                    ]);
+//            } else {
+//                // 插入新记录
+//                $mongo->name('inventory_summary')->insert($insertData);
+//            }
+//
+//            // 插入库存明细记录
+//            $mongo->name('inventory_records')->insert($insertData);
+//        }
+//        $this->success('添加成功');
+//
+//    }
+
+//    public function add_bach()
+//    {
+//        if ($this->request->isAjax() === false) {
+//            $this->error('请求错误');
+//        }
+//
+//        $data = input('row');
+//        if (empty($data)) {
+//            $this->error('参数错误');
+//        }
+//
+//        $data = json_decode($data, true); // 解码为关联数组
+//
+//        if (json_last_error() !== JSON_ERROR_NONE) {
+//            $this->error('JSON解析错误');
+//        }
+//
+//        if (!isset($data['products']) || empty($data['products'])) {
+//            $this->error('产品数据不能为空');
+//        }
+//
+//        $userinfo = Session::get('admin'); // 获取用户信息
+//        if (empty($userinfo) || !isset($userinfo['company'])) {
+//            $this->error('用户信息获取失败');
+//        }
+//
+//            $mongo = \think\Db::connect('mongodb');
+//            $collection = $userinfo['company'] . '_qcode_bach';
+//            $bachsummary = $userinfo['company'] . '_qcode_bachsummary';
+//
+//            $insertData = [];
+//            $currentday = date('Y-m-d');
+//            $currentTime = date('Y-m-d H:i:s');
+//
+//            foreach ($data['products'] as $product) {
+//
+//                // 计算相关数量
+//                $small_num = 20; // 每一箱数量
+//                $tray_num = 6;   // 每层箱数【箱/层】
+//                $box_num = 3;    // 每托层数【层/托】
+//                $total_boxes = $tray_num * $box_num; // 每托盘箱数【箱/托】= 6*3=18
+//
+//                // 计算总箱数和托盘数
+//                $remaining_quantity = (int)$product['remaining_quantity'];
+//                $larger_num = ceil($remaining_quantity / $small_num); // 总箱数 = 剩余数量/每箱数量(向上取整)
+//                $large_num = ceil($larger_num / $total_boxes);        // 本次打包托盘数 = 总箱数/每托盘箱数(向上取整)
+//
+//                $insertData[] = [
+//                    //登录用户字段信息
+//                    'userid' => $userinfo['id'],//用户id
+//                    'supplier_id' => $userinfo['id'],//用户id
+//                    'supplier_code' => $userinfo['printer_code'],//供应商编码
+//                    'supplier_name' => $data['company_name'],//公司名称
+//
+//                    // 产品字段信息
+//                    'pallet' => '1-'.$large_num,//托盘序号
+//                    'matter_no' => $product['gdbh'],//生产批次号-工单编号
+//                    'matter_id' => $product['gdbh'],
+//                    'matter_type' => '01',
+//                    'order_ddbh' => $product['order_ddbh'],//销售订单号
+//                    'cpbm' => $product['cpbm'],//成品编码
+//                    'matter_name' => $product['cpmc'],//成品名称
+//                    'remark' => $product['remark'],
+//
+//                    'num_danwei' => '2',//单位
+//                    'danwei' => '套',//单位
+//                    'num' => $remaining_quantity,//总数量(张/个)
+//                    'small_num' => $small_num,//每一箱数量
+//                    'tray_num' => $tray_num,//每层箱数【箱/层】
+//                    'box_num' => $box_num,//每托层数【 层/托】
+//                    'total_boxes' => $total_boxes,//每托盘箱数【箱/托】
+//                    'large_num' => $large_num,//本次打包托盘数
+//                    'larger_num' => $larger_num,//总箱数
+//                    'pallet_height' => '1.05',//每托高度
+//                    'pallet_length' => '0.9',//托盘规格
+//                    'pallet_width' => '1.2',//托盘规格
+//
+//                    'l_reservation' => '',
+//                    'l_flow' => '1',//大件流水
+//                    'l_weight' => '',//大件重量
+//                    's_flow' => '',//小件流水
+//                    's_weight' => '',//小件重量
+//                    's_reservation' => '',
+//                    'bach_status' => 0,
+//                    'bach_num' => $product['gdbh'],//生产批次号-工单编号
+//                    'large_endnum' => $large_num,
+//
+//                    // 其他字段信息
+//                    'manufacture_date' => '',//生产日期
+//                    'print_date' => '',//打码日期
+//                    'sys_rq' => $currentday,//新增日期
+//                    'created_at' => $currentTime,//新增时间
+//                    'create_time' => time(),//新增时间
+//                    'updated_at' => '',
+//                    'sync_flag' => '0',
+//                    'delete_time' => '',
+//                    'delect_time' => ''//删除时间
+//                ];
+//            }
+//echo "<pre>";
+//print_r($insertData_bachsummary);
+//echo "<pre>";die;
+//
+//
+//            if (!empty($insertData)) {
+//                //汇总数据
+//                $mongo->name($bachsummary)->insertAll($insertData_bachsummary);
+//                //明细数据
+//                $mongo->name($collection)->insertAll($insertData);
+//                $this->success('添加成功');
+//            } else {
+//                $this->error('没有有效数据可添加');
+//            }
+//
+//    }
+
+
     /**
      * 增加新批次
      */
@@ -184,11 +718,12 @@ class QcodeAdd extends Backend{
 
         $data = [];
         foreach ($rows as $value){
-           foreach ($value as $k=>$v){
-               $data[$k] = $v;
-           }
+            foreach ($value as $k=>$v){
+                $data[$k] = $v;
+            }
         }
 
+
         //打印信息
 
 //        echo "接口获取";echo "<pre>";print_r($data);echo "<pre>";die;
@@ -423,7 +958,8 @@ class QcodeAdd extends Backend{
                 $large_id = $large->getLastInsID();
                 if ($large_id){
 //                    //小件码循环插入
-                    for ($j=0;$j<$data['tray_num'] and ($j+$i*$data['tray_num'])<$batchList['small_num'];$j++){
+//                    for ($j=0;$j<$data['tray_num'] and ($j+$i*$data['tray_num'])<$batchList['small_num'];$j++){
+                    for ($j=0;$j<$data['total_boxes'] and ($j+$i*$data['total_boxes'])<$batchList['total_boxes'];$j++){
                         $small = new QcodeSmall();
                         $s_flow = $this->intTochar($batchList['s_flow']+$j+$i*$data['tray_num']+$lastNum['last_num'],6);//小件码序号从1开始
                         $s_weight = $this->intTochar($batchList['s_weight'],6);
@@ -496,25 +1032,25 @@ class QcodeAdd extends Backend{
      * @param $reservation
      * @return array
      */
-     function CodeData($sign,$fixed_code,$small_num,$print_date,$flow,$weight,$large_sign,$reservation){
-         $code=$sign;//4 位固定标志位
-         $code.=$fixed_code; // 固定字符串
-         $code.=$small_num;//3位 小件数量
-         $code.=$print_date;//6 位 日期
-         $code.=$flow;//6位打印流水号
-         $code.=$weight;//6位辅料重量
-         $code.=$large_sign;//大小件标示位
-
-         $code.=$reservation;//20 位 预留号
-
-         //大码数据信息
-         $data=[
-             'code'=>str_replace(" ","",$code),
-             'code_cp1'=>$print_date.$flow,
-             'code_cp2'=>$weight.$reservation,//20位补充
-             'print_date'=>time(),
-             'p_nums'=>0,
-         ];
-         return $data;
-     }
+    function CodeData($sign,$fixed_code,$small_num,$print_date,$flow,$weight,$large_sign,$reservation){
+        $code=$sign;//4 位固定标志位
+        $code.=$fixed_code; // 固定字符串
+        $code.=$small_num;//3位 小件数量
+        $code.=$print_date;//6 位 日期
+        $code.=$flow;//6位打印流水号
+        $code.=$weight;//6位辅料重量
+        $code.=$large_sign;//大小件标示位
+
+        $code.=$reservation;//20 位 预留号
+
+        //大码数据信息
+        $data=[
+            'code'=>str_replace(" ","",$code),
+            'code_cp1'=>$print_date.$flow,
+            'code_cp2'=>$weight.$reservation,//20位补充
+            'print_date'=>time(),
+            'p_nums'=>0,
+        ];
+        return $data;
+    }
 }

+ 38 - 0
application/admin/controller/QcodeBach.php

@@ -153,8 +153,44 @@ class QcodeBach extends Backend
 //                ->skip($offset)
                 ->select();
 
+
+
+
+
             $qcodeSmall = new QcodeSmall();
             foreach ($list as $k=>$v) {
+
+                $bach_detail = $this->model
+                    ->name($company_id . '_qcode_bach')
+                    ->where('_id', $filter['bach_id'])
+                    ->find();
+
+                $num = (float)$bach_detail['num'];
+                $small_num = (float)$bach_detail['small_num'];
+                $boxes_per_pallet = (float)$bach_detail['total_boxes'];
+
+                $larger_num = $num / $small_num;
+                $full_pallets = floor($larger_num / $boxes_per_pallet);
+                $last_pallet_boxes = fmod($larger_num, $boxes_per_pallet); // 真正浮点取余
+
+
+                $total_pallets = $full_pallets + ($last_pallet_boxes > 0 ? 1 : 0);
+
+                // 当前是第几托(code中解析)
+                $current_flow_str = substr($v['code'], 53, 6);
+                $current_flow = (int) ltrim($current_flow_str, '0');
+                $total_pallets = (int) $total_pallets;
+
+                // 是否是最后一托
+                $is_last = ($current_flow === $total_pallets) ? 1 : 0;
+
+                // 修正箱数
+                $total_boxes = $boxes_per_pallet;
+                if ($is_last && $last_pallet_boxes > 0) {
+                    // 精准保留1位小数,不做四舍五入
+                    $total_boxes = number_format($last_pallet_boxes, 1, '.', '');
+                }
+
                 $oid = $v['_id']->jsonSerialize();
                 $list[$k]['id'] = $oid['$oid'];
                 //设置当前托盘号
@@ -164,6 +200,8 @@ class QcodeBach extends Backend
                     ->where('large_id',$oid['$oid'])
                     ->count();
                 $list[$k]['small_num'] = $small_num;
+                $list[$k]['tray_num'] = $bach_detail['tray_num'];
+                $list[$k]['total_boxes'] = $total_boxes;
                 //设置当前大件重量
                 $list[$k]['l_weight'] = floatval($v['l_weight'])/100;
 

+ 28 - 4
application/admin/view/deliver/apply.html

@@ -1,8 +1,12 @@
 <style>
-    /* 默认背景颜色 */
+     /*默认背景颜色 */
     .table tbody tr.selected {
         background-color: yellow !important;  /* 选中行背景色为黄色 */
     }
+     .table-detail tbody tr.selected {
+         background-color: yellow !important;  /* 选中行背景色为黄色 */
+     }
+
 </style>
 <div class="row" style="font-size: 12px;">
     <div class="panel panel-default panel-intro">
@@ -11,11 +15,13 @@
                 <div class="tab-pane fade active in row" id="one">
                     <div class="widget-body no-padding">
                         <div id="toolbar" class="toolbar">
-                            <a href="javascript:;" class="btn btn-primary btn-refresh" title="{:__('Refresh')}" ><i class="fa fa-refresh"></i> </a>
-                            <a href="javascript:;" class="btn btn-success  btn-goods btn-disabled disabled {:$auth->check('deliver/goods')?'':'hide'}" title="发货" ><i class="glyphicon glyphicon-export"></i>发货</a>
+                            <a href="javascript:;" class="btn btn-primary btn-refresh" title="{:__('Refresh')}" ><i class="fa fa-refresh"></i> 刷新</a>
                         </div>
                         <table id="table2" class="table table-striped table-bordered table-hover table-nowrap"
                                data-operate-edit=""
+                               data-search="false" data-show-toggle="false"
+                               data-show-columns="false" data-show-export="false"
+                               data-common-search="false"
                                data-operate-del="{:$auth->check('deliver/apply_del')}"
                                width="100%">
                         </table>
@@ -25,4 +31,22 @@
         </div>
     </div>
 </div>
-
+<div class="row" style="font-size: 12px;">
+    <div class="panel panel-default panel-intro">
+        <div class="panel-body">
+            <div class="tab-content">
+                <div class="tab-pane fade active in row" id="two">
+                    <div class="widget-body no-padding">
+                        <table id="table-detail"
+                               class="table table-striped table-bordered table-hover"
+                               data-search="false" data-show-toggle="false"
+                               data-show-columns="false" data-show-export="false"
+                               data-common-search="false"
+                               width="100%">
+                        </table>
+                    </div>
+                </div>
+            </div>
+        </div>
+    </div>
+</div>

+ 28 - 0
application/admin/view/deliver/bachids.html

@@ -0,0 +1,28 @@
+<style>
+    .table tbody tr.selected {
+        background-color: yellow !important;
+    }
+</style>
+
+<div class="row" style="font-size: 12px;">
+    <div class="panel panel-default panel-intro">
+        <div class="panel-body">
+            <div class="tab-content">
+                <div class="tab-pane fade active in row" id="one">
+                    <div class="widget-body no-padding">
+                        <div id="toolbar" class="toolbar">
+                            <a href="javascript:;" class="btn btn-primary btn-refresh" title="{:__('Refresh')}"><i class="fa fa-refresh"></i> 刷新</a>
+                        </div>
+                        <table id="table-detail"
+                               class="table table-striped table-bordered table-hover"
+                               data-search="false" data-show-toggle="false"
+                               data-show-columns="false" data-show-export="false"
+                               data-common-search="false"
+                               width="100%">
+                        </table>
+                    </div>
+                </div>
+            </div>
+        </div>
+    </div>
+</div>

+ 9 - 8
application/admin/view/deliver/index.html

@@ -12,11 +12,11 @@
 </style>
 <div class="panel-heading">
     <ul id="myTab" class="nav nav-tabs">
+<!--        <li class="active">-->
+<!--            <a href="#iframe1" id="lager" data-toggle="tab">大件发货</a>-->
+<!--        </li>-->
         <li class="active">
-            <a href="#iframe1" id="lager" data-toggle="tab">大件发货</a>
-        </li>
-        <li>
-            <a href="#iframe2" id="apply" data-toggle="tab">批次发货申请</a>
+            <a href="#iframe2" id="apply" data-toggle="tab">打托调整页</a>
         </li>
         <li>
             <a href="#iframe3" id="dispatch" data-toggle="tab">发货单</a>
@@ -24,10 +24,11 @@
     </ul>
 </div>
 <div id="myTabContent" class="tab-content">
-    <div class="tab-pane fade in active" id="iframe1">
-        <iframe src="lager" allowtransparency="true" scrolling="no" frameborder="0" style="width: 100%;height: 800px;"></iframe>
-    </div>
-    <div class="tab-pane fade" id="iframe2">
+<!--    <div class="tab-pane fade in active" id="iframe1">-->
+<!--        <iframe src="lager" allowtransparency="true" scrolling="no" frameborder="0" style="width: 100%;height: 800px;"></iframe>-->
+<!--    </div>-->
+<!--    <div class="tab-pane fade" id="iframe2">-->
+        <div class="tab-pane fade in active" id="iframe2">
         <iframe src="apply" allowtransparency="true" scrolling="no" frameborder="0" style="width: 100%;height: 800px"></iframe>
     </div>
     <div class="tab-pane fade" id="iframe3">

+ 2 - 1
application/admin/view/finishedproduct/index.html

@@ -261,7 +261,8 @@
 
 <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
-<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
+<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
+<!--<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>-->
 <script src="https://cdn.jsdelivr.net/npm/layer/dist/layer.js"></script>
 <script>
     $(function() {

+ 421 - 404
application/admin/view/qcode_add/index.html

@@ -1,5 +1,9 @@
 <style>
-    table tr th,table tr td {border: thin #ddd dashed;padding: 5px }
+    table tr th, table tr td {
+        border: thin #ddd dashed;
+        padding: 5px
+    }
+
     .select2-container {
         width: 400px !important;
     }
@@ -7,17 +11,21 @@
     .select2-dropdown {
         width: 400px !important;
     }
+
     .select2-results__options {
-        max-height: 200px;   /* 固定高度 */
-        overflow-y: auto;    /* 超出时出现滚动条 */
+        max-height: 200px;
+        overflow-y: auto;
     }
-    .select2-container--default .select2-selection--single .select2-selection__clear{
+
+    .select2-container--default .select2-selection--single .select2-selection__clear {
         margin-top: -6px;
     }
-    .select2-container--default .select2-selection--single .select2-selection__rendered{
+
+    .select2-container--default .select2-selection--single .select2-selection__rendered {
         line-height: 35px;
     }
-    .select2-container--default .select2-selection--single{
+
+    .select2-container--default .select2-selection--single {
         width: 470px !important;
         height: 35px !important;
         line-height: 38px;
@@ -27,17 +35,19 @@
         border-radius: 4px;
         box-sizing: border-box;
     }
-    .select2-container--open .select2-dropdown--below{
+
+    .select2-container--open .select2-dropdown--below {
         margin-top: -13px;
     }
-    .selection{
+
+    .selection {
         top: -13px;
     }
-    /*table部分*/
+
     .selected-row {
-        /*background-color: yellow !important;*/
         background-color: #ddefeb !important;
     }
+
     #pagination-wrapper {
         margin-top: 20px;
         font-family: Arial, sans-serif;
@@ -49,9 +59,9 @@
         justify-content: center;
         align-items: center;
         flex-wrap: nowrap;
-        gap: 16px; /* 控制 info 和按钮间距 */
+        gap: 16px;
         white-space: nowrap;
-        overflow-x: auto; /* 小屏幕自动横向滚动,防止换行 */
+        overflow-x: auto;
     }
 
     #pagination-info {
@@ -89,21 +99,61 @@
         font-weight: bold;
         border-color: #007bff;
     }
+
     #table-container {
-        height: 300px; /* 你可以按需调整高度 */
+        height: 200px;
         overflow-y: auto;
         border: 1px solid #ccc;
         margin-bottom: 10px;
     }
 
-    /* 让表头固定,表体滚动(可选进阶) */
     #table thead th {
         position: sticky;
         top: 0;
         background-color: #f5f5f5;
         z-index: 1;
     }
+
+    .tray-btn {
+        padding: 5px 10px;
+        margin-right: 8px;
+        border: 1px solid #ccc;
+        background-color: white;
+        color: #000;
+        cursor: pointer;
+        border-radius: 4px;
+    }
+
+    .tray-btn.active {
+        background-color: #007bff;
+        color: white;
+        border-color: #007bff;
+    }
+
+    .remove-btn {
+        color: red;
+        cursor: pointer;
+        margin-left: 10px;
+    }
+
+    #tableBody tr {
+        cursor: pointer;
+    }
+
+    #tableBody tr:hover {
+        background-color: #f0f0f0;
+    }
+
+    #tableBody1 tr td {
+        padding: 8px;
+    }
+
+    .total-row {
+        font-weight: bold;
+        background-color: #f5f5f5;
+    }
 </style>
+
 <form id="add-form" class="form-horizontal" role="form" data-toggle="validator" method="POST" action="">
     <fieldset style="width: 1200px;margin:10px 10px 0px 10px ;padding: 10px 10px 0px 10px ;border:solid thin #c0c0c0">
         <legend style="padding: 0px;margin: 0px">生成厂商信息</legend>
@@ -134,33 +184,33 @@
     </fieldset>
 
     <fieldset style="width: 1200px;margin:10px 10px 0px 10px ;padding: 10px 10px 0px 10px ;border: solid thin #c0c0c0">
-        <legend style="padding: 0px;margin: 0px">产品信息</legend>
-        <!-- 搜索栏 -->
+        <legend style="padding: 0px;margin: 0px">打托选择列表</legend>
         <div style="margin-bottom: 10px;">
-            <input type="text" id="searchInput"  placeholder="请输入关键字搜索..." style="width: 300px;height: 35px; " />
-            <button id="searchBtn"  class="btn btn-primary">搜索</button>
+            <input type="text" id="searchInput" placeholder="请输入关键字搜索..." style="width: 300px;height: 35px; "/>
+            <button type="text" id="searchBtn" className="btn btn-primary" style="height: 34px">查询</button>
+            &nbsp;
+            <button id="sadBtn" class="btn btn-success">
+                <i class="fas fa-plus"></i> 新增产品
+            </button>
         </div>
 
-        <!-- 表格容器 -->
         <div id="table-container">
-        <table id="table" border="1" cellpadding="8" cellspacing="0" style="width: 100%;border-collapse: collapse;">
-            <thead>
-            <tr>
-                <th>销售订单号</th>
-                <th>工单编号</th>
-                <th>成品编码</th>
-                <th>成品名称</th>
-                <th>入库数</th>
-                <th>发货数</th>
-                <th>剩余数</th>
-            </tr>
-            </thead>
-            <tbody id="tableBody">
-
-            </tbody>
-        </table>
+            <table id="table" style="width: 100%;border-collapse: collapse;">
+                <thead>
+                <tr>
+                    <th>销售订单号</th>
+                    <th>工单编号</th>
+                    <th>成品编码</th>
+                    <th>成品名称</th>
+                    <th>入库数</th>
+                    <th>发货数</th>
+                    <th>剩余数</th>
+                </tr>
+                </thead>
+                <tbody id="tableBody">
+                </tbody>
+            </table>
         </div>
-        <!-- 分页控件 -->
         <div id="pagination-wrapper">
             <div id="pagination-bar">
                 <div id="pagination-info">共 0 条记录,第 1 / 1 页</div>
@@ -170,200 +220,30 @@
     </fieldset>
 
     <fieldset style="width: 1200px;margin:10px 10px 0px 10px ;padding: 10px 10px 0px 10px ;border: solid thin #c0c0c0">
-<!--        <legend  style="padding: 0px;margin: 0px">托盘参数</legend>-->
-        <table style="width: 100%;border: thin #ddd dashed;">
-<!--            <caption style="padding: 0px;margin: 0px">标签序列配置</caption>-->
-<!--            <tr>-->
-<!--                <th style="width: 40%">字段</th>-->
-<!--                <th>值</th>-->
-<!--            </tr>-->
-            <tr>
-                <td><span>生产批次号/工单编号</span></td>
-                <td style="padding: 5px 0px 0px 5px"><input type="text" disabled class="form-control" placeholder="选择产品信息获取" id="c-batch" name="batch" style="width: 360px;"></td>
-            </tr>
-            <tr>
-                <td><span>销售订单号</span></td>
-                <td style="padding: 5px 0px 0px 5px"><input type="text" disabled class="form-control" placeholder="选择产品信息获取" id="c-order_ddbh" name="order_ddbh" style="width: 360px;"></td>
-            </tr>
-            <tr>
-                <td><span>成品编码</span></td>
-                <td style="padding: 5px 0px 0px 5px"><input type="text" disabled class="form-control" placeholder="选择产品信息获取" id="c-cpbm" name="cpbm" style="width: 360px;"></td>
-            </tr>
-            <tr>
-                <td><span>成品名称</span></td>
-                <td style="padding: 5px 0px 0px 5px"><input type="text" disabled class="form-control" placeholder="选择产品信息获取" id="c-cpmc" name="cpmc" style="width: 360px;"></td>
-            </tr>
-            <tr style="display: none">
-                <td><span>入库数</span></td>
-                <td style="padding: 5px 0px 0px 5px"><input type="text"  disabled class="form-control" placeholder="选择产品信息获取" id="c-sl" name="sl" style="width: 360px;"></td>
-            </tr>
-            <tr style="display: none">
-                <td><span>发货数</span></td>
-                <td style="padding: 5px 0px 0px 5px"><input type="text" disabled class="form-control" placeholder="选择产品信息获取" id="c-total_chu_quantity" name="total_chu_quantity" style="width: 360px;"></td>
-            </tr>
-            <tr>
-                <td><span>剩余数</span></td>
-                <td style="padding: 5px 0px 0px 5px"><input type="text" disabled class="form-control" placeholder="选择产品信息获取" id="c-remaining_quantity" name="remaining_quantity" style="width: 360px;"></td>
-            </tr>
-
-            <tr class="xiang">
-                <td><span>本次打包数</span></td>
-                <td style="padding: 5px 0px 0px 5px"><input type="text" oninput="validateAndCalculate()" name="number" id="c-number" data-rule="required"></td>
-            </tr>
-            <tr>
-                <td><span>选择单位(个/套/张)</span></td>
-                <td style="padding: 5px 0px 0px 5px">
-                    <select id="danwei" name="danwei" style="width: 200px;padding: 5px;">
-                        <option value="1">个</option>
-                        <option value="2">套</option>
-                        <option value="3">张</option>
-                    </select>
-                </td>
-            </tr>
-
-            <tr class="xiang">
-                <td><span>每一箱数量</span></td>
-                <td style="padding: 5px 0px 0px 5px">
-                    <select name="box_number" id="box_number" oninput="calculateTotalBoxes()" style="width:200px;padding: 5px">
-                        <option value="1">========选择=========</option>
-                        <option value="20">========20========</option>
-                        <option value="25">========25========</option>
-                        <option value="25">========40========</option>
-                        <option value="50">========50========</option>
-                        <option value="250">========250========</option>
-                        <option value="500">========500========</option>
-                        <option value="1000">=======1000========</option>
-                        <option value="2000">=======2000========</option>
-                        <option value="2500">=======2500========</option>
-                        <option value="3000">=======3000========</option>
-                        <option value="4000">=======4000========</option>
-                        <option value="5000">=======5000========</option>
-                        <option value="8000">=======8000========</option>
-                        <option value="10000">=======10000========</option>
-                        <option value="24000">=======24000========</option>
-                    </select>
-                </td>
-            </tr>
-
-            <tr class="xiang">
-                <td><span>一托盘多少箱(箱*层)</span></td>
-                <td style="padding: 5px 0px 0px 5px">
-                    <input type="text" id="tray_num"     oninput="calculateTotalBoxes()" style="width: 100px;" min="1" step="1" > 箱/层 ×
-                    <input type="text" id="tray_number"  oninput="calculateTotalBoxes()" style="width: 100px;"  min="1" step="1" > 层/托 =
-                    <input type="text" id="total_boxes"  style="width: 100px;" disabled> 箱/托
-                    <span style="color: red;font-size: 23px;"> *</span>
-                </td>
-            </tr>
-
-            <tr>
-                <td><span>本次打包托盘数(大件数)</span></td>
-                <td style="padding: 5px 0px 0px 5px"><input type="text" id="c-box_num" disabled name="box_num" ></td>
-            </tr>
-            <tr>
-                <td><span>总箱数</span></td>
-                <td style="padding: 5px 0px 0px 5px"><input type="text" id="c-small_num" disabled name="small_num" data-rule="required"></td>
-            </tr>
-
-            <tr>
-                <td><span>每托高度(米/m)</span></td>
-                <td style="padding: 5px 0px 0px 5px; position: relative;">
-                    <input type="text" id="pallet_height" name="pallet_height"
-                           style="width: 160px;" placeholder="" autocomplete="off">
-                    <ul id="height-suggestions" style=" position: absolute;
-                                top: 33px; left: 5px; width: 160px;
-                                border: 1px solid #ccc; background: #fff; list-style: none;
-                                margin: 0; padding: 0; display: none; z-index: 1000;">
-                        <li style="padding: 5px; cursor: pointer;">0.995</li>
-                        <li style="padding: 5px; cursor: pointer;">1.05</li>
-                        <li style="padding: 5px; cursor: pointer;">1.35</li>
-                    </ul>
-                    <span style="color: red; font-size: 23px;"> *</span>
-                </td>
-            </tr>
-
-            <tr>
-                <td><span>托盘规格(例如:0.9 * 1.2)</span></td>
-                <td style="padding: 5px 0px 0px 5px; position: relative;">
-                    <div style="display: inline-block; position: relative;">
-                        <input type="text" id="pallet_length" name="pallet_length" style="width:80px;" autocomplete="off">
-                        <ul id="length-suggestions" style="
-                                position: absolute;
-                                top: 28px;
-                                left: 0;
-                                width: 80px;
-                                border: 1px solid #ccc;
-                                background: #fff;
-                                list-style: none;
-                                margin: 0;
-                                padding: 0;
-                                display: none;
-                                z-index: 1000;">
-                            <li style="padding: 5px; cursor: pointer;">0.9</li>
-                            <li style="padding: 5px; cursor: pointer;">1.0</li>
-                            <li style="padding: 5px; cursor: pointer;">1.1</li>
-                        </ul>
-                    </div>
-                    &nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
-                    *
-                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
-                    <div style="display: inline-block; position: relative;">
-                        <input type="text" id="pallet_width" name="pallet_width" style="width:80px;"   autocomplete="off">
-                        <ul id="width-suggestions" style="
-                                position: absolute;
-                                top: 28px;
-                                left: 0;
-                                width: 80px;
-                                border: 1px solid #ccc;
-                                background: #fff;
-                                list-style: none;
-                                margin: 0;
-                                padding: 0;
-                                display: none;
-                                z-index: 1000;">
-                            <li style="padding: 5px; cursor: pointer;">1.1</li>
-                            <li style="padding: 5px; cursor: pointer;">1.2</li>
-                            <li style="padding: 5px; cursor: pointer;">1.3</li>
-                        </ul>
-                    </div>
-                    <span style="color: red;font-size: 23px;"> *</span>
-                </td>
-            </tr>
-            <tr>
-                <td><span>生产日期</span></td>
-                <td style="padding: 5px 0px 0px 5px">
-                    <input class="" id="c-manufacture_date" value="{:date('Y-m-d')}" style="width: 180px;" name="manufacture_date" type="date" >
-                </td>
-            </tr>
-            <tr>
-                <td><span>打码日期</span></td>
-                <td style="padding: 5px 0px 0px 5px">
-                    <input class="" type="date" id="c-print_date" style="width: 180px"  name="print_date" value="{:date('Y-m-d')}">
-                </td>
-            </tr>
-            <tr>
-                <td><span>大件开始流水号</span></td>
-                <td>
-                    <div style="display: flex; align-items: center;">
-                        <input type="text" name="big_liushui" id="c-big_liushui" disabled>
-                        <button type="button" id="reset_liushui" style="margin-left: 10px;">重置流水号</button>
-                    </div>
-                </td>
-            </tr>
-
-            <tr>
-                <td><span>大件重量(单位千克数值)有小数时保留2位小数</span></td>
-                <td style="padding: 5px 0px 0px 5px"><input type="text" id="c-big_weight" name="big_weight" data-rule="required"><span style="color: red;font-size: 23px;"> *</span></td>
-            </tr>
-            <tr>
-                <td><span>小件开始流水号</span></td>
-                <td style="padding: 5px 0px 0px 5px"><input type="text" id="c-small_start_liushui" name="small_start_liushui" value="1" ></td>
-            </tr>
-            <tr>
-                <td><span>小件重量(单位克 数值)</span></td>
-                <td style="padding: 5px 0px 0px 5px"><input type="text" id="c-small_weight" name="small_weight" data-rule="required"><span style="color: red;font-size: 23px;"> *</span></td>
-            </tr>
-
-        </table>
+        <legend style="padding: 0px;margin: 0px">打托选品列表</legend>
+        <div id="table-container1">
+            <table id="table1" style="width: 100%;border-collapse: collapse;">
+                <thead>
+                <tr>
+                    <th>序号</th>
+                    <th>产品名称</th>
+                    <th>应发货数量</th>
+                    <th>实际发货数量</th>
+                    <th>备注</th>
+                    <th>操作</th>
+                </tr>
+                </thead>
+                <tbody id="tableBody1">
+                </tbody>
+                <tfoot id="tableFooter1" style="display: none;">
+                <tr className="total-row">
+                    <td colSpan="2">合计</td>
+                    <td id="totalQuantity">0</td>
+                    <td colSpan="2"></td>
+                </tr>
+                </tfoot>
+            </table>
+        </div>
     </fieldset>
 
     <div class="form-group layer-footer">
@@ -372,83 +252,101 @@
             <button type="submit" id="submit" class="btn btn-primary btn-embossed">保存</button></div>
     </div>
 </form>
-<!-- 引入 select2 样式 -->
-<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
-<!-- 引入 jQuery -->
-<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
-<!-- 引入 select2 JS -->
-<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
+
 <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
+<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
 <script>
-    $(function() {
-        const $input = $('#pallet_height');
-        const $list = $('#height-suggestions');
-        // 显示下拉菜单
-        $input.on('focus click', function () {
-            $list.show();
-        });
-        // 点击选项
-        $list.on('click', 'li', function () {
-            $input.val($(this).text());
-            $list.hide();
-        });
-        // 失焦隐藏
-        $input.on('blur', function () {
-            setTimeout(() => $list.hide(), 100); // 延迟防止刚点 li 时被关闭
-        });
-    });
-
     let currentPage = 1;
     let limit = 10;
     let total = 0;
     let selectedRow = null;
+    let selectedProducts = [];
 
-    // 绑定全局选择函数
     window.selectRow = function (row) {
-        console.log('行数据:', row);
-
         if (selectedRow) {
             $(selectedRow).removeClass('selected-row');
         }
         $(row).addClass('selected-row');
         selectedRow = row;
+    };
+
+    function addToShipment(row) {
+        console.log($(row).data('remaining_quantity'))
+        if($(row).data('remaining_quantity') == 0){
+            layer.msg('库存数量为空!', {icon: 2});
+            return;
+        }
 
         const rowData = {
             gdbh: $(row).data('gdbh'),
             order_ddbh: $(row).data('order_ddbh'),
             cpbm: $(row).data('cpbm'),
             cpmc: $(row).data('cpmc'),
-            sl: $(row).data('sl'),
-            total_chu_quantity: $(row).data('total_chu_quantity'),
-            remaining_quantity: $(row).data('remaining_quantity')
+            remaining_quantity: $(row).data('remaining_quantity'),
+            remark: ''
         };
 
-        console.log('选中的行数据:', rowData);
+        const exists = selectedProducts.some(item => item.gdbh === rowData.gdbh);
+        if (exists) {
+            layer.msg('该产品已添加到本次配货中!', {icon: 2});
+            return;
+        }
+
+        selectedProducts.push(rowData);
+        renderShipmentTable();
+    }
 
-        $('#c-batch').val(rowData['gdbh']);
-        $('#c-order_ddbh').val(rowData['order_ddbh']);
-        $('#c-cpbm').val(rowData['cpbm']);
-        $('#c-cpmc').val(rowData['cpmc']);
-        $('#c-sl').val(rowData['sl']);
-        $('#c-total_chu_quantity').val(rowData['total_chu_quantity']);
+    function removeFromShipment(index) {
+        selectedProducts.splice(index, 1);
+        renderShipmentTable();
+    }
 
-        // 新增这段判断
-        if (parseFloat(rowData['remaining_quantity']) >= 0) {
-            $('#c-remaining_quantity').val(rowData['remaining_quantity']);
-        } else {
-            $('#c-remaining_quantity').val('');
+    function calculateTotalQuantity() {
+        return selectedProducts.reduce((sum, product) => sum + (parseFloat(product.remaining_quantity) || 0), 0);
+    }
+
+    function renderShipmentTable() {
+        const tbody = $('#tableBody1');
+        tbody.empty();
+
+        if (selectedProducts.length === 0) {
+            tbody.append('<tr><td colspan="5" style="text-align:center;">暂无配货数据</td></tr>');
+            $('#tableFooter1').hide();
+            return;
         }
-    };
+
+        selectedProducts.forEach((product, index) => {
+            const tr = $(`
+                <tr>
+                    <td>${index + 1}</td>
+                    <td>${product.cpmc}</td>
+                    <td>${product.remaining_quantity}</td>
+                    <td><input type="text" class="quantity-input" data-index="${index}" value="${product.actual_quantity || product.remaining_quantity || ''}" placeholder="" style="width:100%;"></td>
+                    <td><input type="text" class="remark-input" data-index="${index}" value="${product.remark || ''}" placeholder="请输入备注" style="width:100%;"></td>
+                    <td><span class="remove-btn" onclick="removeFromShipment(${index})">移除</span></td>
+                </tr>
+            `);
+            tbody.append(tr);
+        });
+
+        $('#tableFooter1').show();
+        $('#totalQuantity').text(calculateTotalQuantity());
+
+        // 绑定备注输入事件 - 修正后的实现
+        $('.remark-input').off('input').on('input', function () {
+            const index = $(this).data('index');
+            const remark = $(this).val();
+            if (selectedProducts[index]) {
+                selectedProducts[index].remark = remark;
+            }
+        });
+    }
 
     function loadData(page = 1, keyword = '') {
         $.ajax({
             method: "GET",
-            url: "/qcode_add/product", // 替换成你的接口路径
-            data: {
-                page: page,
-                limit: limit,
-                search: keyword
-            },
+            url: "/qcode_add/product",
+            data: {page, limit, search: keyword},
             dataType: "json",
             success: function (res) {
                 const data = res.data || [];
@@ -460,15 +358,13 @@
                 tbody.empty();
                 selectedRow = null;
 
-                if (!Array.isArray(data) || data.length === 0) {
-                    tbody.append('<tr><td colspan="5">无数据</td></tr>');
+                if (data.length === 0) {
+                    tbody.append('<tr><td colspan="7">无数据</td></tr>');
                     return;
                 }
 
-                $('#c-big_liushui').val(1)
-
                 data.forEach(item => {
-                const tr = $(`
+                    const tr = $(`
                         <tr onclick="selectRow(this)"
                             data-order_ddbh="${item.order_ddbh}"
                             data-gdbh="${item.gdbh}"
@@ -477,7 +373,6 @@
                             data-sl="${item.sl}"
                             data-total_chu_quantity="${item.total_chu_quantity}"
                             data-remaining_quantity="${item.remaining_quantity}">
-
                             <td>${item.order_ddbh}</td>
                             <td>${item.gdbh}</td>
                             <td>${item.cpbm}</td>
@@ -503,152 +398,274 @@
         wrapper.empty();
         info.text(`共 ${total} 条记录,第 ${currentPage} / ${pageCount} 页`);
 
-        // 上一页按钮
         const prev = $('<button type="button">上一页</button>').prop('disabled', currentPage <= 1);
-        prev.on('click', (e) => {
-            e.preventDefault();
-            e.stopPropagation(); // 防止事件冒泡
-            loadData(currentPage - 1, keyword);
-        });
+        prev.on('click', () => loadData(currentPage - 1, keyword));
         wrapper.append(prev);
 
-        // 页码按钮
         const start = Math.max(1, currentPage - 1);
         const end = Math.min(pageCount, currentPage + 1);
         for (let i = start; i <= end; i++) {
             const btn = $('<button type="button"></button>').text(i);
             if (i === currentPage) btn.addClass('active');
-            btn.on('click', (e) => {
-                e.preventDefault();
-                e.stopPropagation();
-                loadData(i, keyword);
-            });
+            btn.on('click', () => loadData(i, keyword));
             wrapper.append(btn);
         }
 
-        // 下一页按钮
         const next = $('<button type="button">下一页</button>').prop('disabled', currentPage >= pageCount);
-        next.on('click', (e) => {
-            e.preventDefault();
-            e.stopPropagation();
-            loadData(currentPage + 1, keyword);
-        });
+        next.on('click', () => loadData(currentPage + 1, keyword));
         wrapper.append(next);
     }
 
+    $(function () {
+        loadData();
 
-    //搜索按钮
-    $('#searchBtn').on('click', function (e) {
-        e.preventDefault();
-        const keyword = $('#searchInput').val().trim();
-        loadData(1, keyword);
-    });
-    //搜索input框
-    $('#searchInput').on('keypress', function (e) {
-        if (e.which === 13) {
+
+
+        $('#searchBtn').on('click', function (e) {
+            e.preventDefault();
             const keyword = $('#searchInput').val().trim();
             loadData(1, keyword);
-        }
-    });
+        });
 
-    $(function () {
-        loadData(1);
-    });
+        $('#searchInput').on('keypress', function (e) {
+            if (e.which === 13) {
+                const keyword = $(this).val().trim();
+                loadData(1, keyword);
+            }
+        });
 
-    function allowNumberAndDot(input) {
-        input.value = input.value.replace(/[^\d.]/g, '')    // 只保留数字和小数点
-        .replace(/^\./g, '')      // 开头不能是小数点
-        .replace(/\.{2,}/g, '.')  // 不能连续两个点
-        .replace(/(\.\d*)\./g, '$1'); // 只允许一个小数点
-    }
+        $(document).on('click', '#tableBody tr', function () {
+            addToShipment(this);
+        });
 
+        // 修改sadBtn的点击事件处理
+        $('#sadBtn').on('click', function (e) {
+            e.preventDefault();
 
-    //托盘规格
-    $('#pallet_length, #pallet_width').on('input', function() {
-        allowNumberAndDot(this);
-    });
-    // 绑定 pallet_length 的下拉选择
-    $('#pallet_length').on('focus input', function () {
-        $('#length-suggestions').show();
-    });
-    $('#length-suggestions li').on('click', function () {
-        $('#pallet_length').val($(this).text());
-        $('#length-suggestions').hide();
-    });
-    // 绑定 pallet_width 的下拉选择
-    $('#pallet_width').on('focus input', function () {
-        $('#width-suggestions').show();
-    });
-    $('#width-suggestions li').on('click', function () {
-        $('#pallet_width').val($(this).text());
-        $('#width-suggestions').hide();
-    });
-    // 点击空白区域时隐藏建议框
-    $(document).on('click', function (e) {
-        if (!$(e.target).closest('#pallet_length, #length-suggestions').length) {
-            $('#length-suggestions').hide();
-        }
-        if (!$(e.target).closest('#pallet_width, #width-suggestions').length) {
-            $('#width-suggestions').hide();
-        }
-    });
+            // 生成一行表格的HTML
+            const generateRowHtml = (index) => `
+        <tr data-row="${index}">
+            <td><input type="text" name="order_ddbh" class="form-control" required /></td>
+            <td><input type="text" name="gdbh" class="form-control" required /></td>
+            <td><input type="text" name="cpbm" class="form-control" required /></td>
+            <td><input type="text" name="cpmc" class="form-control" required /></td>
+            <td><input type="number" name="sl" class="form-control" min="1" required /></td>
+            <td>
+                <button type="button" class="btn btn-success btn-xs add-row"><i class="fa fa-plus"></i></button>
+                <button type="button" class="btn btn-danger btn-xs remove-row"><i class="fa fa-minus"></i></button>
+            </td>
+        </tr>
+    `;
+
+            layer.open({
+                type: 1,
+                title: '新增入库记录',
+                area: ['90%', '70%'],
+                shadeClose: true,
+                resize: true,
+                maxmin: true,
+                btn: ['加入选品列表', '取消'],
+                content: `
+            <div style="padding: 20px 30px;">
+                <table class="table table-bordered" id="productTable">
+                    <thead>
+                        <tr>
+                            <th>销售订单号</th>
+                            <th>工单编号</th>
+                            <th>成品编码</th>
+                            <th>成品名称</th>
+                            <th>入库数</th>
+                            <th>操作</th>
+                        </tr>
+                    </thead>
+                    <tbody>
+                        ${generateRowHtml(0)}
+                    </tbody>
+                </table>
+            </div>
+        `,
+                success: function(layero, index) {
+                    // 添加行事件
+                    $(layero).on('click', '.add-row', function() {
+                        const tbody = $('#productTable tbody');
+                        const newRowIndex = tbody.find('tr').length;
+                        tbody.append(generateRowHtml(newRowIndex));
+                    });
+
+                    // 删除行事件
+                    $(layero).on('click', '.remove-row', function() {
+                        const row = $(this).closest('tr');
+                        if ($('#productTable tbody tr').length > 1) {
+                            row.remove();
+                        } else {
+                            layer.msg('至少保留一行', {icon: 2});
+                        }
+                    });
+                },
+                yes: function(index) {
+                    const newProducts = [];
+                    let isValid = true;
+
+                    $('#productTable tbody tr').each(function() {
+                        const rowData = {};
+                        let rowValid = true;
+
+                        $(this).find('[required]').each(function() {
+                            const $input = $(this);
+                            const val = $input.val().trim();
+
+                            if (!val) {
+                                layer.tips('此项为必填项', $input, {tips: [1, '#FF5722']});
+                                isValid = false;
+                                rowValid = false;
+                                return false; // 退出当前each循环
+                            }
+
+                            rowData[$input.attr('name')] = val;
+                        });
+
+                        if (rowValid) {
+                            // 设置剩余数量等于入库数量(因为是新增产品)
+                            rowData.remaining_quantity = rowData.sl;
+                            rowData.total_chu_quantity = 0; // 发货数量初始为0
+                            rowData.isNew = true; // 标记为新增产品
+                            newProducts.push(rowData);
+                        }
+                    });
+
+                    if (!isValid || newProducts.length === 0) {
+                        if (newProducts.length === 0) {
+                            layer.msg('请至少填写一行有效数据', {icon: 2});
+                        }
+                        return;
+                    }
+
+                    // 将新产品添加到选品列表
+                    newProducts.forEach(product => {
+                        // 检查是否已存在相同工单编号的产品
+                        const exists = selectedProducts.some(item => item.gdbh === product.gdbh);
+                        if (!exists) {
+                            selectedProducts.push({
+                                gdbh: product.gdbh,
+                                order_ddbh: product.order_ddbh,
+                                cpbm: product.cpbm,
+                                cpmc: product.cpmc,
+                                remaining_quantity: product.remaining_quantity,
+                                total_chu_quantity: product.total_chu_quantity,
+                                isNew: true, // 标记为新增产品
+                                remark: ''
+                            });
+                        }
+                    });
+
+                    layer.msg(`成功添加 ${newProducts.length} 个产品到选品列表`, {icon: 1});
+                    layer.close(index);
+                    renderShipmentTable();
+                }
+            });
+        });
 
-    function validateAndCalculate() {
-        let input = document.getElementById('c-number');
-        let remainingInput = document.getElementById('c-remaining_quantity');
-        let max = parseInt(remainingInput.value, 10);
+// 修改提交处理逻辑
+        $('#submit').off('click').on('click', function (e) {
+            e.preventDefault();
 
-        // 判断库存是否为空或非法
-        if (!remainingInput.value || isNaN(max)) {
-            input.value = '';
-            layer.msg('库存数量为空,无法输入!', {icon: 2});
-            return;
-        }
+            if (selectedProducts.length === 0) {
+                layer.msg('请至少选择一个产品添加到打托选品列表!', {icon: 2});
+                return false;
+            }
 
-        // 只允许输入数字(去除字母、负号、小数点等)
-        input.value = input.value.replace(/[^\d]/g, '');
-        let val = parseInt(input.value, 10);
+            // 确保所有输入数据已更新
+            $('.quantity-input').each(function() {
+                const index = $(this).data('index');
+                const value = $(this).val() || $(this).attr('value') || '';
+                selectedProducts[index].actual_quantity = value;
+            });
 
-        // 判断是否超出库存
-        if (!isNaN(val) && val > max) {
-            layer.msg('输入值不能超过库存数量!', {icon: 0});
-            input.value = max;
-        }
+            $('.remark-input').each(function() {
+                const index = $(this).data('index');
+                const value = $(this).val() || '';
+                selectedProducts[index].remark = value;
+            });
+
+            // 分离新增产品和已有产品
+            const newProducts = selectedProducts.filter(p => p.isNew);
+            const existingProducts = selectedProducts.filter(p => !p.isNew);
+
+            const postData = {
+                company_name: $('#c-company_name').val(),
+                postcode: $('#c-postcode').val(),
+                mobile: $('#c-mobile').val(),
+                company_address: $('#c-company_address').val(),
+                printer_code: $('#c-printer_code').val(),
+                products: selectedProducts.map(p => ({
+                    ...p,
+                    remark: p.remark || '',
+                    actual_quantity: p.actual_quantity || p.remaining_quantity
+                })),
+                newProducts: newProducts.map(p => ({
+                    order_ddbh: p.order_ddbh,
+                    gdbh: p.gdbh,
+                    cpbm: p.cpbm,
+                    cpmc: p.cpmc,
+                    sl: p.remaining_quantity,
+                    remark: p.remark || '',
+                    actual_quantity: p.actual_quantity || p.remaining_quantity
+                }))
+            };
+
+            // 显示加载中
+            const loadingIndex = layer.msg('处理中...', {icon: 16, shade: 0.3, time: 0});
+
+            // 先处理新增产品入库
+            if (newProducts.length > 0) {
+                $.ajax({
+                    method: "POST",
+                    url: "Finishedproduct/finished",
+                    contentType: "application/json",
+                    data: JSON.stringify({ data: postData.newProducts }),
+                    success: function(res) {
+                        if (res && res.code === 1) {
+                            // 新增产品入库成功后,提交主表单
+                            submitMainForm(postData, loadingIndex);
+                        } else {
+                            layer.close(loadingIndex);
+                            layer.msg(res?.msg || '新增产品入库失败', {icon: 2});
+                        }
+                    },
+                    error: function(xhr) {
+                        layer.close(loadingIndex);
+                        const errorMsg = xhr.responseJSON?.message || xhr.statusText || '请求失败';
+                        layer.msg('新增产品入库失败: ' + errorMsg, {icon: 2});
+                    }
+                });
+            } else {
+                // 没有新增产品,直接提交主表单
+                submitMainForm(postData, loadingIndex);
+            }
+        });
 
-        // 调用原始计算逻辑
-        calculateTotalBoxes();
-    }
-
-
-    //一托盘多少箱
-    function calculateTotalBoxes() {
-        // 获取用户输入
-        const number = parseInt(document.getElementById("c-number").value || 0);         // 本次打包数
-        const box_number = parseInt(document.getElementById("box_number").value || 0);   // 每一箱数量(个)
-        const tray_num = parseInt(document.getElementById("tray_num").value || 0);       // 每层的箱数(箱/层)
-        const tray_layer = parseInt(document.getElementById("tray_number").value || 0);  // 层数(层/托)
-        // 计算每托盘能放多少箱
-        const boxes_per_tray = tray_num * tray_layer;
-        document.getElementById("total_boxes").value = boxes_per_tray; // 自动填充 total_boxes(箱/托)字段
-        // 计算总箱数(向上取整)
-        // const totalBoxCount = Math.ceil(number / box_number);
-        const totalBoxCount = Math.ceil(number / box_number);
-        // 计算托盘数(向上取整)
-        const trayCount = Math.ceil(totalBoxCount / boxes_per_tray);
-
-        console.log("本次打包数:", number);
-        console.log("每箱数量:", box_number);
-        console.log("总箱数:", totalBoxCount);
-        console.log("每托盘箱数:", boxes_per_tray);
-        console.log("本次托盘数:", trayCount);
-        if(trayCount == 'Infinity'){
-            document.getElementById("c-box_num").value = 0;
-        }else{
-            document.getElementById("c-box_num").value = trayCount;
-            document.getElementById("c-small_num").value = totalBoxCount;
+        // 提交主表单的函数
+        function submitMainForm(postData, loadingIndex) {
+            Fast.api.ajax({
+                url: 'qcode_add/add_bach',
+                type: 'POST',
+                data: {row: JSON.stringify(postData)},
+            }, function (data, res) {
+                layer.close(loadingIndex);
+                if (res.code == 1) {
+                    layer.msg('保存成功', {icon: 1});
+                    window.location.reload();
+                    // 或者跳转到其他页面
+                    // Backend.api.addtabs('deliver/apply');
+                } else {
+                    layer.msg(res.msg || '保存失败', {icon: 2});
+                }
+            }, function () {
+                layer.close(loadingIndex);
+                layer.msg('请求失败', {icon: 2});
+            });
         }
-        // 填入最终托盘数(大件数)
-        // $('#c-box_num').val(trayCount);
-    }
+    });
+
 
 </script>

+ 297 - 100
public/assets/js/backend/deliver.js

@@ -1,7 +1,13 @@
-define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {
+define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'editable'], function ($, undefined, Backend, Table, Form,undefined) {
 
     var Controller = {
         index: function () {
+            // $('#lager').on('click', function () {
+            //     const iframe = document.querySelector('#iframe1 iframe');
+            //     if (iframe) {
+            //         iframe.src = iframe.src; // 强制 reload iframe
+            //     }
+            // });
             $('#apply').on('click', function () {
                 const iframe = document.querySelector('#iframe2 iframe');
                 if (iframe) {
@@ -15,9 +21,9 @@ define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefin
                 }
             });
 
-            $('#lager').click(function () {
-                $('#iframe1').contentWindow.location.reload('lager.html');
-            });
+            // $('#lager').click(function () {
+            //     $('#iframe1').contentWindow.location.reload('lager.html');
+            // });
             Controller.api.bindevent();
         },
         // lager: function () {
@@ -230,84 +236,258 @@ define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefin
                 extend: {
                     index_url: 'deliver/apply' + location.search,
                     goods_url: 'deliver/goods',
-                    del_url:'deliver/apply_del',
-                    table:'deliver'
+                    del_url: 'deliver/apply_del',
+                    table: 'deliver',
+                    update_url: 'deliver/apply_update'
                 }
             });
 
             var table = $("#table2");
+            var detailTable = $("#table-detail");
 
-            // 初始化表格
+            // 初始化表格
             table.bootstrapTable({
                 url: $.fn.bootstrapTable.defaults.extend.index_url,
                 pk: 'id',
-                height:400,
+                // height: 300,
                 sortName: 'id',
-                searchFormVisible:true,
-                search:false,
-                showToggle:false,
-                showColumns:false,
-                showExport:false,
-                fixedColumns: true,
-                fixedRightNumber: 1,
+                searchFormVisible: true,
+                search: false,
+                showToggle: false,
+                showColumns: false,
+                showExport: false,
+                fixedColumns: false,
+                onClickRow: function(row, $element) {
+                    // 移除之前选中的行样式
+                    table.find('tr.selected').removeClass('selected');
+                    // 添加当前选中行样式
+                    $element.addClass('selected');
+
+                    // 加载明细数据
+                    detailTable.bootstrapTable('refresh', {
+                        url: 'deliver/bachids?bach_ids=' + encodeURIComponent(row.bach_ids)
+                    });
+                },
+                onEditableSave: function (field, row, oldValue, $el) {
+                    // Send AJAX request to save the changes
+                    $.ajax({
+                        url: $.fn.bootstrapTable.defaults.extend.update_url,
+                        type: 'POST',
+                        data: {
+                            id: row.id,
+                            field: field,
+                            value: row[field]
+                        },
+                        success: function (data) {
+                            if (data.code !== 1) {
+                                // If update fails, revert the change
+                                $el.bootstrapTable('updateCell', {
+                                    index: row._index,
+                                    field: field,
+                                    value: oldValue
+                                });
+                                Toastr.error(data.msg || '更新失败');
+                            } else {
+                                Toastr.success('更新成功');
+                            }
+                        },
+                        error: function () {
+                            // On error, revert the change
+                            $el.bootstrapTable('updateCell', {
+                                index: row._index,
+                                field: field,
+                                value: oldValue
+                            });
+                            Toastr.error('网络错误,更新失败');
+                        }
+                    });
+                },
                 columns: [
                     [
-                        {checkbox: true},
-                        {field: 'id', title: __('Id'),visible:false,operate: false},
-                        {field: 'large_num', title: '托盘数量', operate: false},
-                        {field: 'matter_name', title: '产品名称', operate: 'LIKE',searchList: $.getJSON("deliver/matterName")},
+                        // {checkbox: true},
+                        {field: 'id', title: __('Id'), visible: false, operate: false},
+                        {field: 'bach_ids', title: '单据编号', operate: false},
+                        {field: 'total_quantity', title: '总发货数量', operate: false},
+                        {field: 'total_boxes', title: '总箱数', operate: false},
+                        {field: 'total_pallets', title: '总托盘数', operate: false},
+                        {field: 'product_count', title: '产品数量', operate: false},
+                        {field: 'sys_rq', title: '日期', operate: false},
+                        {field: 'created_at', title: '操作时间', operate: false},
+                        {
+                            field: 'operate',
+                            title: '操作',
+                            align: 'center',
+                            formatter: function(value, row, index) {
+                                return '<a href="javascript:;" class="btn-goods btn btn-xs btn-success" data-id="' + row.id + '"><i class="glyphicon glyphicon-export"></i> 发货</a>';
+                            }
+                        }
+                    ]
+                ]
+            });
+
+            // 发货按钮事件
+            table.on('click', '.btn-goods', function(e) {
+                e.stopPropagation();
+                var id = $(this).data('id');
+                Fast.api.open('deliver/goods?ids=' + id, '发货信息', {area: ["60%", "60%"]});
+            });
+
+            // 初始化明细表格
+            detailTable.bootstrapTable({
+                pk: 'id',
+                sortName: 'id',
+                search: false,
+                pagination: true,           // 开启分页
+                pageSize: 50,               // 设置每页显示数量,设为大于总数据量即可显示全部
+                pageList: [10, 25, 50, 100],// 可选的每页显示数量
+                height: 400,
+                // sidePagination: 'server',
+                // pageSize: 10,
+                toolbar: '#toolbar-detail',
+                onEditableSave: function (field, row, oldValue, $el) {
+                    $.ajax({
+                        url: $.fn.bootstrapTable.defaults.extend.update_url,
+                        type: 'POST',
+                        data: {
+                            id: row.id,
+                            field: field,
+                            value: row[field]
+                        },
+                        success: function (data) {
+                            if (data.code !== 1) {
+                                $el.bootstrapTable('updateCell', {
+                                    index: row._index,
+                                    field: field,
+                                    value: oldValue
+                                });
+                                Toastr.error(data.msg || '更新失败');
+                            } else {
+                                Toastr.success('更新成功');
+                            }
+                        },
+                        error: function () {
+                            $el.bootstrapTable('updateCell', {
+                                index: row._index,
+                                field: field,
+                                value: oldValue
+                            });
+                            Toastr.error('网络错误,更新失败');
+                        }
+                    });
+                },
+                columns: [
+                    [
+                        // {checkbox: true},
+                        {field: 'id', title: __('Id'), visible: false, operate: false},
+                        {field: 'pallet', title: '序号',  operate: false},
+                        {field: 'pallet_sequence', title: '托盘序号', operate: false,
+                            editable: {
+                                type: 'text',
+                                title: '托盘序号'
+                            },
+                            formatter: function(value, row, index) {
+                                return value ? value : '无';
+                            }
+                        },
+                        {field: 'order_ddbh', title: '销售订单号', operate: false},
+                        {field: 'matter_no', title: '工单编号', operate: false},
+                        {field: 'cpbm', title: '成品编码', operate: false},
+                        {field: 'matter_name', title: '产品名称', operate: 'LIKE', searchList: $.getJSON("deliver/matterName")},
+                        {field: 'num', title: '本次发货数量', operate: false},
+                        {field: 'small_num', title: '每一箱数量', operate: false,
+                            editable: {
+                                type: 'number',
+                                title: '每一箱数量',
+                                validate: function (v) {
+                                    if (!v) return '不能为空';
+                                    if (isNaN(v)) return '必须为数字';
+                                }
+                            }
+                        },
                         {field: 'total_boxes', title: '每箱托数', operate: false},
-                        {field: 'tray_num', title: '每层箱数', operate: false},
-                        {field: 'box_num', title: '每托层数', operate: false},
-                        {field: 'pallet_height', title: '托盘高度', operate: false},
+                        {field: 'tray_num', title: '每层箱数', operate: false,
+                            editable: {
+                                type: 'number',
+                                title: '每层箱数',
+                                validate: function (v) {
+                                    if (!v) return '不能为空';
+                                    if (isNaN(v)) return '必须为数字';
+                                }
+                            }
+                        },
+                        {field: 'box_num', title: '每托层数', operate: false,
+                            editable: {
+                                type: 'number',
+                                title: '每托层数',
+                                validate: function (v) {
+                                    if (!v) return '不能为空';
+                                    if (isNaN(v)) return '必须为数字';
+                                }
+                            }
+                        },
                         {
-                            field: 'pallet_size',
-                            title: '托盘规格',
+                            field: 'pallet_height',
+                            title: '每托高度',
                             operate: false,
-                            width: 120,
-                            formatter: function (value, row, index) {
-                                return row.pallet_length + ' * ' + row.pallet_width;
+                            editable: {
+                                type: 'text',
+                                title: '每托高度',
+                                validate: function (v) {
+                                    if (!v) return '不能为空';
+                                    if (isNaN(v)) return '必须为数字';
+                                }
                             }
                         },
-                        // {field: 'small_num', title: '总箱数', operate: false},
-                        {field: 'larger_num', title: '总箱数', operate: false},
-
-                        // {field: 'matter_no', title: '产品编码', operate: false},
-                        {field: 'username', title: '所属用户', operate: 'LIKE'},
-                        // {field: 'large_num', title: '大件数量', operate: false},
-                        // {field: 'small_num', title: '小件数量', operate: false},
-                        {field: 'create_time', title: '创建时间', operate: 'RANGE', addclass: 'datetimerange', formatter: Table.api.formatter.datetime},
-                        {field: 'file_dir', title: '下载路径', operate: false,formatter: function (value,row,index) {
-                                if (row.status == 0){
-                                    return "<a href=/"+value+">点击下载</a>";
-                                }else {
-                                    return "不支持下载";
+                        {
+                            field: 'pallet_length',
+                            title: '托盘长',
+                            operate: false,
+                            editable: {
+                                type: 'text',
+                                title: '托盘长度',
+                                validate: function (v) {
+                                    if (!v) return '不能为空';
+                                    if (isNaN(v)) return '必须为数字';
                                 }
-                            }},
-                        {field: 'status', title: '状态', operate: 'LIKE',searchList: {"0":'待发货',"1":'已删除'}, formatter: Table.api.formatter.status},
-                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
+                            }
+                        },
+                        {
+                            field: 'pallet_width',
+                            title: '托盘宽',
+                            operate: false,
+                            editable: {
+                                type: 'text',
+                                title: '托盘宽度',
+                                validate: function (v) {
+                                    if (!v) return '不能为空';
+                                    if (isNaN(v)) return '必须为数字';
+                                }
+                            }
+                        },
+                        {field: 'large_num', title: '托盘数', operate: false},
+                        {field: 'larger_num', title: '总箱数', operate: false},
+                        {field: 'remark', title: '备注', operate: false,
+                            editable: {
+                                type: 'text',
+                                title: '备注'
+                            },
+                            formatter: function(value, row, index) {
+                                return value ? value : '无';
+                            }
+                        }
                     ]
                 ],
             });
 
-
-            // 为表格绑定事件
+            // 绑定事件
             Table.api.bindevent(table);
+            Table.api.bindevent(detailTable);
 
-            //发货按钮
-            $('.btn-goods').on('click',function () {
-                var ids = Table.api.selectedids(table);
-                if (ids.length === 0){
-                    alert('至少选择一个订单');
-                }
-                var id_str = ids.toString();
-                Fast.api.open('deliver/goods?ids='+id_str,'发货信息',{area:["60%","60%"]})
-            });
-            //去掉时间区间输入记忆
-            table.on('post-body.bs.table',function (e,settings,json,xhr) {
+            // 去掉时间区间输入记忆
+            table.on('post-body.bs.table', function (e, settings, json, xhr) {
                 $('.datetimerange').each(function () {
-                    $(this).attr('autocomplete','off');
-                })
+                    $(this).attr('autocomplete', 'off');
+                });
             });
 
             Controller.api.bindevent();
@@ -407,25 +587,48 @@ define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefin
                                     success: function (data, res) {
                                         if (res.code === 1) {
                                             const arr = res.data.data;
+                                            console.log(res);
 
                                             let totalTray = 0;
                                             let totalBox = 0;
-                                            const productNames = [];
-                                            const productQuantities = [];
 
-                                            // 遍历数据,统计数量
+                                            // 产品名称聚合:{ 名称: { qty: 数量, unit: 单位 } }
+                                            const productMap = {};
+
+                                            // 单位分类统计
+                                            let totalTao = 0;
+                                            let totalZhang = 0;
+                                            let totalGe = 0;
+
+                                            // 累加托盘数、箱数
                                             for (let i = 0; i < arr.length; i++) {
-                                                totalTray += parseInt(arr[i].large_num || 0);
-                                                totalBox += parseInt(arr[i].larger_num || 0);
-                                                productNames.push(arr[i].matter_name);
-                                                productQuantities.push(arr[i].total_boxes * arr[i].larger_num);
-                                            }
+                                                const item = arr[i];
+                                                totalTray += parseInt(item.large_num || 0);
+                                                totalBox += parseInt(item.larger_num || 0);
 
-                                            // 根据出货数量计算手工盒子数量
-                                            const manualBoxes = productQuantities.reduce((total, qty) => total + qty, 0);
+                                                const name = item.matter_name;
+                                                const unit = item.danwei;
+                                                const qty = parseInt(item.num || 0);
 
-                                            // 纸质卡片数量可按业务设定(例:每托2张)
-                                            const paperCards = totalTray * totalBox;
+                                                if (!productMap[name]) {
+                                                    productMap[name] = { qty: 0, unit: unit };
+                                                }
+                                                productMap[name].qty += qty;
+
+                                                // 单位分类汇总
+                                                if (unit === '套') {
+                                                    totalTao += qty;
+                                                } else if (unit === '张') {
+                                                    totalZhang += qty;
+                                                } else if (unit === '个') {
+                                                    totalGe += qty;
+                                                }
+                                            }
+
+                                            const productNames = Object.keys(productMap);
+                                            const productQuantities = productNames.map(name => productMap[name].qty);
+                                            const manualBoxes = productQuantities.reduce((a, b) => a + b, 0);
+                                            const paperCards = 0; // 按你的业务逻辑这里可自定义
 
                                             let html = `
                                             <div style="width: 1100px; height: 100px; position: relative;">
@@ -455,23 +658,24 @@ define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefin
                                     
                                             <table style="width: 1070px; border-collapse: collapse; table-layout: fixed; font-size: 16px; text-align: center; margin-top: 0;">
                                                 <tr style="font-weight: bold;">
-                                                    <th style="border: 1px solid black;text-align: center;">托盘序号</th>
-                                                    <th style="border: 1px solid black;text-align: center; width: 360px;">产品名称</th>
-                                                    <th style="border: 1px solid black;text-align: center;">每箱数</th>
-                                                    <th style="border: 1px solid black;text-align: center;">每箱数</th>
-                                                    <th style="border: 1px solid black;text-align: center;">每层数</th>
-                                                    <th style="border: 1px solid black;text-align: center;">每托高度</th>
-                                                    <th style="border: 1px solid black;text-align: center;">托盘规格</th>
-                                                    <th style="border: 1px solid black;text-align: center;">托盘</th>
-                                                    <th style="border: 1px solid black;text-align: center;">总箱数</th>
-                                                </tr>
-                                            `;
+                                                 <th style="border: 1px solid black;text-align: center;">托盘序号</th>
+                                                                                        <th style="border: 1px solid black;text-align: center; width: 360px;">产品名称</th>
+                                                                                        <th style="border: 1px solid black;text-align: center;">每箱数</th>
+                                                                                        <th style="border: 1px solid black;text-align: center;">每箱数</th>
+                                                                                        <th style="border: 1px solid black;text-align: center;">每层数</th>
+                                                                                        <th style="border: 1px solid black;text-align: center;">每托层数</th>
+                                                                                        <th style="border: 1px solid black;text-align: center;">每托高度</th>
+                                                                                        <th style="border: 1px solid black;text-align: center;">托盘规格</th>
+                                                                                        <th style="border: 1px solid black;text-align: center;">托盘数</th>
+                                                                                        <th style="border: 1px solid black;text-align: center;">总箱数</th>
+                                                </tr>`;
 
                                                                                 for (let i = 0; i < arr.length; i++) {
                                                                                     html += `
                                                 <tr>
-                                                    <td style="border: 1px solid black;">第${arr[i].large_ber}托</td>
+                                                    <td style="border: 1px solid black;">第${arr[i].pallet}托</td>
                                                     <td style="border: 1px solid black;">${arr[i].matter_name}</td>
+                                                    <td style="border: 1px solid black;">${arr[i].small_num}</td>
                                                     <td style="border: 1px solid black;">${arr[i].total_boxes}</td>
                                                     <td style="border: 1px solid black;">${arr[i].tray_num}</td>
                                                     <td style="border: 1px solid black;">${arr[i].box_num}</td>
@@ -479,8 +683,7 @@ define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefin
                                                     <td style="border: 1px solid black;">${arr[i].pallet_length} * ${arr[i].pallet_width}</td>
                                                     <td style="border: 1px solid black;">${arr[i].large_num}</td>
                                                     <td style="border: 1px solid black;">${arr[i].larger_num}</td>
-                                                </tr>
-                                                `;
+                                                </tr>`;
                                                                                 }
 
                                                                                 const fillCount = 15 - arr.length;
@@ -496,8 +699,8 @@ define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefin
                                                     <td style="border: 1px solid black;"></td>
                                                     <td style="border: 1px solid black;"></td>
                                                     <td style="border: 1px solid black;"></td>
-                                                </tr>
-                                                `;
+                                                    <td style="border: 1px solid black;"></td>
+                                                </tr>`;
                                                                                 }
 
                                                                                 html += `
@@ -509,6 +712,7 @@ define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefin
                                                 <td style="border: 1px solid black;"></td>
                                                 <td style="border: 1px solid black;"></td>
                                                 <td style="border: 1px solid black;"></td>
+                                                <td style="border: 1px solid black;"></td>
                                                 <td style="border: 1px solid black;">${totalTray}</td>
                                                 <td style="border: 1px solid black;">${totalBox}</td>
                                             </tr>
@@ -517,7 +721,7 @@ define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefin
                                             <table style="margin-top: 20px; width: 1070px; border-collapse: collapse; font-size: 18px;">
                                                 <tr>
                                                     <td colspan="${productNames.length + 2}" style="border: 1px solid black; text-align: left;">
-                                                        总共出货:${totalBox} 箱 = ${totalTray} 托(手工盒子:${manualBoxes} 套,纸质卡片:${paperCards} 张
+                                                        总共出货:${totalBox} 箱 = ${totalTray} 托(手工盒子:${totalTao} 套,纸质卡片:${totalZhang} 张,${totalGe} 个
                                                     </td>
                                                 </tr>
                                                 <tr>
@@ -527,7 +731,7 @@ define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefin
                                                 </tr>
                                                 <tr>
                                                     <td style="border: 1px solid black; text-align: center;">出货数量</td>
-                                                    ${productQuantities.map(qty => `<td style="border: 1px solid black; text-align: center;">${qty}</td>`).join('')}
+                                                    ${productNames.map(name => `<td style="border: 1px solid black; text-align: center;">${productMap[name].qty}</td>`).join('')}
                                                     <td style="border: 1px solid black; text-align: center;">${manualBoxes}</td>
                                                 </tr>
                                             </table>
@@ -539,23 +743,16 @@ define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefin
                                                 <br/>(1) 用唛头笔写上托盘序号,托盘唛头打印贴在每托盘上面,打托的时候混托注意摆放和高度,另外不要漏掉了。
                                                 <br/>(2) 每托烟盒中间放瓦楞,最上面盖个木板,缠绕膜缠结实,护角护好,打打包带,井子形打包
                                                 <br/>(3) 配托后,请提供具体托盘高度及托盘重量。
-                                            </div>
-        `;
+                                            </div>`;
 
                                             $("#printcode").html(html);
-                                            var ee = $('#qrcode_image').attr('src',res.data.qrcode_add);
-                                            // 将打印的区域赋值,进行打印
-                                            ee.on('load',function () {
+                                            var ee = $('#qrcode_image').attr('src', res.data.qrcode_add);
+                                            ee.on('load', function () {
                                                 var printHTML = document.querySelector('#printcode').innerHTML;
                                                 window.document.body.innerHTML = printHTML;
                                                 window.print();
-                                                window.location.reload(); // 打印完成后重新加载页面
-                                            })
-
-                                            // const printHTML = document.querySelector('#printcode').innerHTML;
-                                            // document.body.innerHTML = printHTML;
-                                            // window.print();
-                                            // window.location.reload();
+                                                window.location.reload();
+                                            });
                                         }
                                         return false;
                                     },

+ 66 - 219
public/assets/js/backend/qcode_add.js

@@ -110,225 +110,72 @@ define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefin
             });
 
             //点击保存按钮
-            $('#submit').click(function () {
-                var rows = $.makeArray();
-                //生产厂商
-                var company_name = $('#c-company_name').val();
-                if (company_name == null || company_name === ''){
-                    layer.confirm('生产厂商不能为空');
-                }
-                rows.push({'company_name':company_name});
-                //邮政编码
-                var postcode = $('#c-postcode').val();
-                if (postcode == null || postcode === ''){
-                    layer.confirm('邮政编码不能为空');
-                }
-                rows.push({'postcode':postcode});
-                //电话
-                var mobile = $('#c-mobile').val();
-                if (mobile == null || mobile === ''){
-                    layer.confirm('电话不能为空');
-                }
-                rows.push({'mobile':mobile});
-                //公司地址
-                var company_address = $('#c-company_address').val();
-                if (company_address == null || company_address === ''){
-                    layer.confirm('公司地址不能为空');
-                }
-                //厂商编码
-                var printer_code = $('#c-printer_code').val();
-                if (printer_code == null || printer_code === '' || printer_code === undefined){
-                    layer.confirm('厂商编码不能为空');
-                }
-                rows.push({'printer_code':printer_code});
-
-                //生产批次号/工单编号
-                var gdbh = $('#c-batch').val();
-                if (gdbh == null || gdbh === ''){
-                    layer.confirm('生产批次号/工单编号不能为空');
-                }
-                rows.push({'gdbh':gdbh});
-                //销售订单号
-                var order_ddbh = $('#c-order_ddbh').val();
-                if (order_ddbh == null || order_ddbh === ''){
-                    layer.confirm('销售订单号不能为空');
-                }
-                rows.push({'order_ddbh':order_ddbh});
-                //成品编号
-                var cpbm = $('#c-cpbm').val();
-                if (cpbm == null || cpbm === ''){
-                    layer.confirm('成品编号不能为空');
-                }
-                rows.push({'cpbm':cpbm});
-                //成品名称
-                var cpmc = $('#c-cpmc').val();
-                if (cpmc == null || cpmc === ''){
-                    layer.confirm('成品名称不能为空');
-                }
-                rows.push({'cpmc':cpmc});
-                //入库数
-                var sl = $('#c-sl').val();
-                if (sl == null || sl === ''){
-                    layer.confirm('入库数为空');
-                }
-                rows.push({'sl':sl});
-                //发货数
-                var total_chu_quantity = $('#c-total_chu_quantity').val();
-                if (total_chu_quantity == null || total_chu_quantity === ''){
-                    layer.confirm('发货数为空');
-                }
-                rows.push({'total_chu_quantity':total_chu_quantity});
-                //剩余数
-                var remaining_quantity = $('#c-remaining_quantity').val();
-                if (remaining_quantity == null || remaining_quantity === ''){
-                    layer.confirm('剩余数为空');
-                }
-                rows.push({'remaining_quantity':remaining_quantity});
-
-                //单位
-                var danwei = $('#danwei').val();
-                if (danwei == null || danwei === ''){
-                    layer.confirm('单位不能为空');
-                }
-                rows.push({'danwei':danwei});
-                //判断选择单位【1=张、2=】
-                // if (danwei === '1'){
-                    //本次打包数
-                    var number = $('#c-number').val();
-                    if (number == null || number === ''){
-                        layer.confirm('本次打包数不能为空');
-                    }
-                    rows.push({'number':number});
-                    //每一箱数量
-                    var box_number = $('#box_number').val();
-                    if (box_number == null || box_number === ''){
-                        layer.confirm('每一箱数量不能为空');
-                    }
-                    rows.push({'box_number':box_number});
-                    //一托盘多少箱
-                    //箱/层
-                    var tray_num =  $('#tray_num').val();
-                    if (tray_num == null || tray_num === ''){
-                        layer.confirm('箱/层不能为空');
-                    }
-                    rows.push({'tray_num':tray_num});
-                    //层/托
-                    var tray_number = $('#tray_number').val();
-                    if (tray_number == null || tray_number === ''){
-                        layer.confirm('层/托不能为空');
-                    }
-                    rows.push({'tray_number':tray_number});
-                    var total_boxes = $('#total_boxes').val();
-                    if (total_boxes == null || total_boxes === ''){
-                        layer.confirm('箱/托不能为空');
-                    }
-                    rows.push({'total_boxes':total_boxes});
-                // }else {
-                //     //一托盘多少卷
-                //     var volume_num = $('#c-volume_num').val();
-                //     if (volume_num == null || volume_num === ''){
-                //         layer.confirm('一坨多少卷不能为空');
-                //     }
-                //     rows.push({'volume_num':volume_num});
-                // }
-
-
-                // //每托盘箱数
-                // var small_num = $('#c-small_num').val();
-                // if (small_num == null || small_num === ''){
-                //     layer.confirm('每托盘箱数不能为空');
-                // }
-                // rows.push({'small_num':small_num});
-
-                //本次打包托盘数(大件数)
-                var box_num = $('#c-box_num').val();
-                if (box_num == null || box_num ===''){
-                    layer.confirm('大件(总托数)不能为空');
-                }
-                rows.push({'box_num':box_num});
-                //总箱数
-                var small_num = $('#c-small_num').val();
-                if (small_num == null || small_num ===''){
-                    layer.confirm('总箱数为空');
-                }
-                rows.push({'small_num':small_num});
-                //每托高度
-                var pallet_height = $('#pallet_height').val();
-                if (pallet_height == null || pallet_height === '' || pallet_height === undefined){
-                    layer.confirm('每托高度不能为空');
-                }
-                rows.push({'pallet_height':pallet_height});
-                //托盘规格
-                var pallet_length = $('#pallet_length').val();
-                if (pallet_length == null || pallet_length === '' || pallet_length === undefined){
-                    layer.confirm('托盘规格不能为空');
-                }
-                rows.push({'pallet_length':pallet_length});
-                //托盘规格
-                var pallet_width = $('#pallet_width').val();
-                if (pallet_width == null || pallet_width === '' || pallet_width === undefined){
-                    layer.confirm('托盘规格不能为空');
-                }
-                rows.push({'pallet_width':pallet_width});
-
-                //生产日期
-                var manufacture_date = $('#c-manufacture_date').val();
-                if (manufacture_date == null || manufacture_date === ''){
-                    layer.confirm('生产日期不能为空');
-                }
-                rows.push({'manufacture_date':manufacture_date});
-                //打码日期
-                var print_date = $('#c-print_date').val();
-                if (print_date == null || print_date === ''){
-                    layer.confirm('打码日期不能为空');
-                }
-                rows.push({'print_date':print_date});
-
-                //大件流水号
-                var big_liushui = $('#c-big_liushui').val();
-                // if (big_liushui == null || big_liushui === ''){
-                //     layer.confirm('大件流水号不能为空');
-                // }
-                rows.push({'big_liushui':big_liushui});
-                //大件重量
-                var big_weight = $('#c-big_weight').val();
-                if (big_weight == null || big_weight === ''){
-                    layer.confirm('大件重量不能为空');
-                }
-                rows.push({'big_weight':big_weight});
-                //小件流水号
-                var small_start_liushui = $('#c-small_start_liushui').val();
-                // if (small_start_liushui == null || small_start_liushui === ''){
-                //     layer.confirm('小件流水号不能为空');
-                // }
-                rows.push({'small_start_liushui':small_start_liushui});
-                //小件重量
-                var small_weight = $('#c-small_weight').val();
-                if (small_weight == null || small_weight === ''){
-                    layer.confirm('小件重量不能为空');
-                }
-                rows.push({'small_weight':small_weight});
-
-                // 打印调试查询
-                // console.log("js判断");
-                // console.log(rows);
-                // return;
-
-                Fast.api.ajax({
-                    url:'qcode_add/add',
-                    type:'POST',
-                    data:{row:JSON.stringify(rows)},
-                },function (data,res) {
-                    console.log(res.code);
-                    if (res.code == 1){
-                        window.location.reload();
-                        Backend.api.addtabs('qcode_bach/index');
-                    }
-                    return false;
-                },function () {
-                    return false;
-                })
-            });
+            // $('#submit').click(function (e) {
+            //     e.preventDefault(); // 阻止表单默认提交行为
+            //
+            //     // 验证是否有选中的产品
+            //     if (selectedProducts.length === 0) {
+            //         layer.msg('请至少选择一个产品添加到打托选品列表!', {icon: 2});
+            //         return false;
+            //     }
+            //
+            //     // 更新selectedProducts中的备注信息(从输入框获取最新值)
+            //     $('.remark-input').each(function() {
+            //         const indexesData = $(this).data('indexes');
+            //         // 确保indexesData存在且是字符串
+            //         if (indexesData && typeof indexesData === 'string') {
+            //             const indexes = indexesData.split(',').map(Number);
+            //             const remark = $(this).val() || '';
+            //             indexes.forEach(index => {
+            //                 if (selectedProducts[index]) {
+            //                     selectedProducts[index].remark = remark;
+            //                 }
+            //             });
+            //         }
+            //     });
+            //
+            //     // 准备要提交的数据
+            //     const postData = {
+            //         company_name: $('#c-company_name').val(),
+            //         postcode: $('#c-postcode').val(),
+            //         mobile: $('#c-mobile').val(),
+            //         company_address: $('#c-company_address').val(),
+            //         printer_code: $('#c-printer_code').val(),
+            //         products: selectedProducts.map(product => ({
+            //             gdbh: product.gdbh,
+            //             order_ddbh: product.order_ddbh,
+            //             cpbm: product.cpbm,
+            //             cpmc: product.cpmc,
+            //             remark: product.remark,
+            //             sl: product.sl,
+            //             total_chu_quantity: product.total_chu_quantity,
+            //             remaining_quantity: product.remaining_quantity
+            //         }))
+            //     };
+            //
+            //     console.log("提交的数据:", postData); // 调试用
+            //
+            //
+            //     // 打印调试查询
+            //     // console.log("js判断");
+            //     // console.log(rows);
+            //     return;
+            //
+            //     Fast.api.ajax({
+            //         url:'qcode_add/add',
+            //         type:'POST',
+            //         data:{row:JSON.stringify(rows)},
+            //     },function (data,res) {
+            //         console.log(res.code);
+            //         if (res.code == 1){
+            //             window.location.reload();
+            //             Backend.api.addtabs('qcode_bach/index');
+            //         }
+            //         return false;
+            //     },function () {
+            //         return false;
+            //     })
+            // });
             Controller.api.bindevent();
         },
         api: {

+ 2 - 3
public/assets/js/backend/qcode_bach.js

@@ -607,9 +607,8 @@ define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'LodopFuncs'], functi
                         [
                             {checkbox: true},
                             {field: 'l_flow', title: __('当前托盘'), operate: false},
-                            // {field: 'l_weight', title: "每托箱数", operate: false},
-                            {field: 'l_num', title: "每托箱数", operate: false},
-                            {field: 'small_num', title:"每层箱数", operate: false},
+                            {field: 'total_boxes', title: "每托箱数", operate: false},
+                            {field: 'tray_num', title:"每层箱数", operate: false},
                             {field: 'print_date', title:__('Print_date'), operate: false},
                             {field: 'p_nums', title:"打印次数", operate: false},
                             {field: 'l_print', title: __('L_print'), operate: false, formatter:function (value, row, index) {

Some files were not shown because too many files changed in this diff