Browse Source

first commit

liuhairui 3 weeks ago
parent
commit
462932cda4

+ 186 - 57
application/admin/controller/Deliver.php

@@ -512,6 +512,7 @@ class Deliver extends Backend
             // 查询数据并按日期排序
             $bach_list = $mongo->name("qcode_goods")
                 ->order('sys_rq', 'desc')
+                ->where('delete_time','')
                 ->select();
 
             // 初始化结果数组
@@ -594,10 +595,8 @@ class Deliver extends Backend
         } elseif ($year) {
             $where['sys_rq'] = new \MongoDB\BSON\Regex($year, 'i');
         } else {
-            // ✅ 默认查询近两天
-            $today = date('Y-m-d');
-            $yesterday = date('Y-m-d', strtotime('-1 day'));
-            $where['sys_rq'] = ['in', [$today, $yesterday]];
+            // 无日期参数时默认查询当天日期
+            $where['sys_rq'] = date('Y-m-d');
         }
 
         // 时间范围查询(高级过滤)
@@ -643,6 +642,98 @@ class Deliver extends Backend
         return json(['total' => $total, 'rows' => $list]);
     }
 
+    public function bachdelids()
+    {
+        $bach_ids = $this->request->param('bach_ids');
+        if (empty($bach_ids)) {
+            return json(['code' => 0, 'msg' => '未查询到要删除的记录']);
+        }
+
+        $userinfo = Session::get('admin');
+        if (empty($userinfo) || !isset($userinfo['company'])) {
+            return json(['code' => 0, 'msg' => '获取用户信息失败,请重新登录']);
+        }
+
+        $mongo = \think\Db::connect('mongodb');
+        $company = $userinfo['company'];
+        $collection = $company . '_qcode_bach';
+        $bachdetails = $company . '_qcode_bachdetails';
+        $bachsummary = $company . '_qcode_bachsummary';
+
+        // 获取批次详情数据
+        $detailData = $mongo->name($collection)
+                     ->where('bach_ids', $bach_ids)
+                     ->select();
+
+        $productQuantities = [];
+        if (!empty($detailData)) {
+            // 按产品名称分组统计实际数量
+            foreach ($detailData as $detail) {
+                $matterName = $detail['cpmc'];
+                $actualQuantity = floatval($detail['actual_quantity']);
+
+                if ($matterName && $actualQuantity > 0) {
+                    if (!isset($productQuantities[$matterName])) {
+                        $productQuantities[$matterName] = 0;
+                    }
+                    $productQuantities[$matterName] += $actualQuantity;
+                }
+            }
+
+            // 处理库存退回
+            foreach ($productQuantities as $productName => $returnQuantity) {
+                // 获取产品最新的库存记录
+                $latestRecord = $mongo->name('inventory_records')
+                    ->where('cpmc', $productName)
+                    ->order('created_at', 'desc')
+                    ->find();
+
+                if (!empty($latestRecord)) {
+                    // 计算新的库存数量并更新库存记录
+                    $newRemainingQuantity = floatval($latestRecord['remaining_quantity'] ?? 0) + $returnQuantity;
+                    $newTotalChuQuantity = max(0, floatval($latestRecord['total_chu_quantity'] ?? 0) - $returnQuantity);
+
+                    $mongo->name('inventory_records')
+                        ->where('_id', $latestRecord['_id'])
+                        ->update([
+                            'remaining_quantity' => $newRemainingQuantity,
+                            'total_chu_quantity' => $newTotalChuQuantity,
+                            'update_time' => time()
+                        ]);
+
+                    // 更新库存汇总表
+                    // 使用cpmc字段进行查询,与文档结构保持一致
+                    $summary = $mongo->name('inventory_summary')
+                        ->where('cpmc', $productName)
+                        ->find();
+
+                    if ($summary) {
+                        $mongo->name('inventory_summary')
+                            ->where('_id', $summary['_id'])
+                            ->update([
+                                'remaining_quantity' => floatval($summary['remaining_quantity'] ?? 0) + $returnQuantity,
+                                'total_chu_quantity' => max(0, floatval($summary['total_chu_quantity'] ?? 0) - $returnQuantity),
+                                'update_time' => time()
+                            ]);
+                    }
+                }
+            }
+        }
+
+        // 标记批次为删除状态
+        $delete_time = time();
+        $mongo->name($collection)->where('bach_ids', $bach_ids)->update(['delete_time' => $delete_time]);
+        $mongo->name($bachdetails)->where('bach_ids', $bach_ids)->update(['delete_time' => $delete_time]);
+        $mongo->name($bachsummary)->where('bach_ids', $bach_ids)->update(['delete_time' => $delete_time]);
+
+        return json([
+            'code' => 1,
+            'msg' => '删除成功,库存已退回',
+            'data' => ['returned_products' => $productQuantities]
+        ]);
+
+    }
+
     /**
      * 明细数据 (通过 bach_ids 获取)
      */
@@ -841,7 +932,7 @@ class Deliver extends Backend
         $value = $this->request->post('value');
 
         // 允许前端编辑的字段
-        $allowedFields = ['pallet_range', 'start_pallet_no', 'end_pallet_no'];
+        $allowedFields = ['pallet_range', 'start_pallet_no', 'end_pallet_no','remark'];
         if (!in_array($field, $allowedFields)) {
             $this->error('该字段不允许编辑');
         }
@@ -908,8 +999,6 @@ class Deliver extends Backend
     /**
      * 司机弹窗
      * @param $ids
-     * @return string
-     * @throws \think\Exception
      */
     public function goods($ids)
     {
@@ -917,12 +1006,16 @@ class Deliver extends Backend
         return $this->view->fetch();
     }
 
+    public function ReplicationList()
+    {
+        $goods = new QcodeGoods();
+        $userinfo = Session::get('admin');
+        //shr_phone电话\plate_number车牌号/deliveryman司机
+        $arr = $goods->where('user_id',$userinfo['id'])->order('create_time','desc')->where("delete_time","")->find();
+        return json(['code' => 1, 'data' => $arr, 'msg' => '成功']);
+    }
     /**
-     * 批次发货提交
-     * @return void
-     * @throws \think\db\exception\DataNotFoundException
-     * @throws \think\db\exception\ModelNotFoundException
-     * @throws \think\exception\DbException
+     * 申请发货
      */
     public function apply_add()
     {
@@ -953,7 +1046,7 @@ class Deliver extends Backend
             $data = [
                 'shdh' => substr($daterq,2,2).' '.substr($daterq,2,6).mt_rand(1000,9999),//收货单号
                 'order_number' => $order_number,//订单号
-                'deliveryman' => $deliveryman,//订单号
+                'deliveryman' => $deliveryman,//司机名字
                 'shr_phone' => $shr_phone,//电话
                 'plate_number' => $plate_number,//车牌号
                 'shrq_date' => '',
@@ -968,7 +1061,9 @@ class Deliver extends Backend
                 'note' => $note,
                 'company_id' => $userinfo['company'],
             ];
-            $data['qrcode_add'] = $this->Qrcode($data['shdh']);
+           $data['qrcode_add'] = $this->Qrcode($data['shdh']);
+//           return json(['code' => 1, 'data' => $data, 'msg' => '成功']);
+
             $res = $goods->save($data);
             if ($res === false){
                 $this->error('失败');
@@ -1063,19 +1158,14 @@ class Deliver extends Backend
         $year = $this->request->get('year', '');
 
         if ($date && $date !== 'all') {
-            // 精确日期查询
             $where['sys_rq'] = $date;
         } elseif ($month) {
-            // 月份模糊查询(如 2023-05)
             $where['sys_rq'] = new \MongoDB\BSON\Regex($month, 'i');
         } elseif ($year) {
-            // 年份模糊查询(如 2023)
             $where['sys_rq'] = new \MongoDB\BSON\Regex($year, 'i');
         } else {
-            // 默认查询近两天数据
-            $today = date('Y-m-d');
-            $yesterday = date('Y-m-d', strtotime('-1 day'));
-            $where['sys_rq'] = ['in', [$today, $yesterday]];
+            // 无日期参数时默认查询当天日期
+            $where['sys_rq'] = date('Y-m-d');
         }
 
         // 分页和排序参数
@@ -1127,44 +1217,28 @@ class Deliver extends Backend
     }
 
     /**
-     * 发货单打印
-     * @return \think\response\Json|void
-     * @throws \think\db\exception\DataNotFoundException
-     * @throws \think\db\exception\ModelNotFoundException
-     * @throws \think\exception\DbException
+     * 打印发货单
      */
     public function printqrcode()
     {
         if (!$this->request->isAjax()) {
             return json(['code' => 0, 'msg' => '请求错误']);
         }
-
         try {
             $mongo = \think\Db::connect('mongodb');
             $userinfo = Session::get('admin');
-
-            if (empty($userinfo) || empty($userinfo['company'])) {
-                return json(['code' => 0, 'msg' => '用户信息获取失败']);
-            }
-
             $goodsCollection = '_qcode_goods';
             $bachCollection = $userinfo['company'] . '_qcode_bach';
             $bachsummaryCollection = $userinfo['company'] . '_qcode_bachsummary';
-
             $id = input('id');
-            if (empty($id)) {
-                return json(['code' => 0, 'msg' => 'ID不能为空']);
-            }
 
+            // 获取发货单数据
             $goodList = $mongo->name($goodsCollection)->where('_id', $id)->find();
             if (empty($goodList)) {
                 return json(['code' => 0, 'msg' => '未找到发货单数据']);
             }
 
-            if (empty($goodList['qcode_bachsummary_id'])) {
-                return json(['code' => 0, 'msg' => '发货单缺少批次汇总ID']);
-            }
-
+            // 获取批次汇总数据
             $bachsummaryData = $mongo->name($bachsummaryCollection)
                 ->where('_id', $goodList['qcode_bachsummary_id'])
                 ->find();
@@ -1172,6 +1246,7 @@ class Deliver extends Backend
                 return json(['code' => 0, 'msg' => '未找到对应的批次汇总数据']);
             }
 
+            // 获取批次数据
             $bachData = $mongo->name($bachCollection)
                 ->where('bach_ids', $bachsummaryData['bach_ids'])
                 ->select();
@@ -1179,6 +1254,7 @@ class Deliver extends Backend
                 return json(['code' => 0, 'msg' => '未找到对应的批次数据']);
             }
 
+            // 初始化数据变量
             $groupedData = [];
             $totalTray = 0;
             $totalBox = 0;
@@ -1187,33 +1263,71 @@ class Deliver extends Backend
             $totalZhang = 0;
             $totalGe = 0;
 
+            // 处理每个批次数据
             foreach ($bachData as $item) {
+                // 数据类型转换和默认值处理
                 $actualQty = is_numeric($item['actual_quantity']) ? (int)$item['actual_quantity'] : 0;
                 $boxCount = is_numeric($item['total_boxes']) ? (int)$item['total_boxes'] : 0;
                 $trayCount = is_numeric($item['pallet_count']) ? (int)$item['pallet_count'] : 0;
 
+                // 累计总数
                 $totalTray += $trayCount;
                 $totalBox += $boxCount;
 
-                $unit = $item['unit'] ?? '个';
+                // 按单位分类累计数量
+                $unit = $item['unit'] ?? '';
                 switch ($unit) {
-                    case '套': $totalTao += $actualQty; break;
-                    case '张': $totalZhang += $actualQty; break;
-                    default:   $totalGe += $actualQty; break;
+                    case '个':
+                    case '套':
+                        $totalTao += $actualQty;
+                        break;
+                    case '张':
+                    case '托':
+                    case '卷':
+                        $totalZhang += $actualQty;
+                        break;
+                    default:
+                        $totalGe += $actualQty;
+                        break;
                 }
 
+                // 处理产品摘要和备注去重
                 $productName = $item['matter_name'] ?? '';
+                $remark = $item['remark'] ?? '';
+
                 if (!isset($productSummary[$productName])) {
-                    $productSummary[$productName] = ['qty' => 0, 'unit' => $unit];
+                    $productSummary[$productName] = ['qty' => 0, 'unit' => $unit, 'remark' => $remark];
+                } else {
+                    // 备注去重处理
+                    if ($remark && $productSummary[$productName]['remark']) {
+                        // 合并备注并去重
+                        $existingRemarks = explode(';', $productSummary[$productName]['remark']);
+                        $newRemarks = explode(';', $remark);
+
+                        // 合并并去除空白项
+                        $allRemarks = array_merge($existingRemarks, $newRemarks);
+                        $trimmedRemarks = array_map('trim', $allRemarks);
+                        $nonEmptyRemarks = array_filter($trimmedRemarks);
+
+                        // 去重并重新拼接
+                        $uniqueRemarks = array_unique($nonEmptyRemarks);
+                        $productSummary[$productName]['remark'] = implode('; ', $uniqueRemarks);
+                    } else if ($remark) {
+                        $productSummary[$productName]['remark'] = $remark;
+                    }
                 }
+
+                // 累计产品数量
                 $productSummary[$productName]['qty'] += $actualQty;
 
+                // 计算每托箱数
                 $boxesPerPallet = (is_numeric($item['tray_num']) && is_numeric($item['box_num']))
                     ? $item['tray_num'] * $item['box_num'] : $boxCount;
 
+                // 添加到分组数据中
                 $groupedData[] = [
                     'pallet' => $item['pallet_range'] ?? '',
-                    'matter_name' => $item['matter_name'] ?? '',
+                    'matter_name' => $productName,
                     'small_num' => $item['small_num'] ?? '',
                     'total_boxes' => $boxesPerPallet,
                     'tray_num' => $item['tray_num'] ?? '',
@@ -1231,22 +1345,37 @@ class Deliver extends Backend
                 ];
             }
 
+            // 处理0值转换为空字符串的函数
+            $convertZeroToEmpty = function($value) {
+                return ($value === 0 || $value === '0') ? '' : $value;
+            };
+
+            // 处理groupedData中的0值
+            foreach ($groupedData as &$dataItem) {
+                foreach ($dataItem as $key => &$value) {
+                    if (is_numeric($value)) {
+                        $value = $convertZeroToEmpty($value);
+                    }
+                }
+            }
+
+            // 构建响应数据
             $responseData = [
                 '_id' => $goodList['_id'],
                 'shrq_date' => date('Y-m-d'),
                 'shdh' => $goodList['shdh'] ?? '',
                 'order_number' => $goodList['order_number'] ?? '',
                 'address' => $goodList['address'] ?? '',
-                'company_id' => $goodList['company_id'] ?? 0,
-                'count' => $goodList['count'] ?? 0,
+                'company_id' => $convertZeroToEmpty($goodList['company_id'] ?? 0),
+                'count' => $convertZeroToEmpty($goodList['count'] ?? 0),
                 'create_time' => $goodList['create_time'] ?? '',
                 'data' => $groupedData,
                 'summary' => [
-                    'totalTray' => $totalTray,
-                    'totalBox' => $totalBox,
-                    'totalTao' => $totalTao,
-                    'totalZhang' => $totalZhang,
-                    'totalGe' => $totalGe,
+                    'totalTray' => $convertZeroToEmpty($totalTray),
+                    'totalBox' => $convertZeroToEmpty($totalBox),
+                    'totalTao' => $convertZeroToEmpty($totalTao),
+                    'totalZhang' => $convertZeroToEmpty($totalZhang),
+                    'totalGe' => $convertZeroToEmpty($totalGe),
                     'products' => $productSummary
                 ],
                 'delete_time' => $goodList['delete_time'] ?? '',
@@ -1257,11 +1386,11 @@ class Deliver extends Backend
                 'plate_number' => $goodList['plate_number'] ?? '',
                 'qrcode_add' => $goodList['qrcode_add'] ?? '',
                 'shr_phone' => $goodList['shr_phone'] ?? '',
-                'status' => $goodList['status'] ?? 0,
-                'supplier_id' => $goodList['supplier_id'] ?? 0,
+                'status' => $convertZeroToEmpty($goodList['status'] ?? 0),
+                'supplier_id' => $convertZeroToEmpty($goodList['supplier_id'] ?? 0),
                 'supplier_name' => $goodList['supplier_name'] ?? '',
-                'sync_flag' => $goodList['sync_flag'] ?? 0,
-                'user_id' => $goodList['user_id'] ?? 0
+                'sync_flag' => $convertZeroToEmpty($goodList['sync_flag'] ?? 0),
+                'user_id' => $convertZeroToEmpty($goodList['user_id'] ?? 0)
             ];
 
             return json(['code' => 1, 'data' => $responseData]);

+ 223 - 896
application/admin/controller/QcodeAdd.php

@@ -98,6 +98,7 @@ class QcodeAdd extends Backend{
             ->order('Sys_rq', 'desc')
             ->select();
 
+
         // 查询 texts = 新增产品 的数据
         $xz_products = $mongo->name('finished_products')
             ->where('texts', '新增产品')
@@ -107,6 +108,7 @@ class QcodeAdd extends Backend{
         // 合并数据
         $all_products = array_merge($al_products, $xz_products);
 
+
         // 分组聚合处理
         $grouped_products = [];
         foreach ($all_products as $item) {
@@ -182,57 +184,50 @@ class QcodeAdd extends Backend{
         ]);
     }
 
+    /**
+     * 添加批次功能
+     *
+     * 功能说明:
+     * 1. 处理AJAX请求,创建产品批次
+     * 2. 自动计算托盘分配(完整托盘和不完整托盘)
+     * 3. 生成批次号和相关统计信息
+     * 4. 更新库存记录
+     * 5. 支持多种托盘配置(18箱/24箱/36箱)
+     */
 //    public function add_bach()
 //    {
-//        // 1. AJAX请求验证
 //        if (!$this->request->isAjax()) {
-//            $this->error('请求必须为AJAX');
+//            $this->error('非法请求,必须使用AJAX方式提交');
 //        }
-//
-//        // 2. 获取并解析输入数据
-//        $data = input('row');
+//        $data = input('row'); // 获取原始数据
 //        if (empty($data)) {
 //            $this->error('请求参数不能为空');
 //        }
-//
 //        $data = json_decode($data, true);
 //        if (json_last_error() !== JSON_ERROR_NONE) {
-//            $this->error('JSON数据解析失败');
+//            $this->error('JSON数据解析失败' . json_last_error_msg());
 //        }
-//
-//        if (empty($data['products'])) {
-//            $this->error('产品数据不能为空');
+//        if (empty($data['products']) || !is_array($data['products'])) {
+//            $this->error('产品数据不能为空且必须是数组');
 //        }
-//
-//        // 3. 用户会话验证
 //        $userinfo = Session::get('admin');
 //        if (empty($userinfo) || !isset($userinfo['company'])) {
 //            $this->error('获取用户信息失败,请重新登录');
 //        }
-//
-//        // 4. MongoDB连接配置
+//        //连接MongoDB
 //        $mongo = \think\Db::connect('mongodb');
+//        //动态生成集合名称(基于公司名称)
 //        $collection = $userinfo['company'] . '_qcode_bach';       // 主表
 //        $bachdetails = $userinfo['company'] . '_qcode_bachdetails'; // 托盘明细表
 //        $bachsummary = $userinfo['company'] . '_qcode_bachsummary'; // 批次汇总表
 //
-//        // 5. 生成批次信息
 //        $currentDate = date('Y-m-d');
 //        $currentDateTime = date('Y-m-d H:i:s');
 //        $timestamp = time();
-//        $bachNum = 'BACH' . date('YmdHis') . mt_rand(1000, 9999); // 批次号规则
-//
-//        // 6. 托盘默认配置
-//        $config = [
-//            'tray_num' => 6,               // 每层6箱
-//            'pallet_length' => '0.9',       // 托盘长度(米)
-//            'pallet_width' => '1.2',        // 托盘宽度(米)
-//            'default_layer_height' => '1.35' // 默认层高(米)
-//        ];
+//        $bachNum = 'BACH' . date('YmdHis') . mt_rand(1000, 9999);
 //
-//        // 7. 初始化统计容器
 //        $batchStats = [
-//            'total_quantity' => 0,     // 总产品数量
+//            'total_quantity' => 0,      // 总产品数量
 //            'total_boxes' => 0,         // 总箱数
 //            'total_pallets' => 0,       // 总托盘数
 //            'full_pallets' => 0,        // 完整托盘数
@@ -240,55 +235,72 @@ class QcodeAdd extends Backend{
 //            'product_varieties' => count($data['products']) // 产品种类数
 //        ];
 //
-//        // 8. 处理每个产品 - 分为两个阶段
 //        $productDetails = [];  // 产品主表数据
 //        $palletDetails = [];   // 托盘明细数据
 //        $currentPalletNo = 1;  // 托盘编号计数器
 //
-//        // 第一阶段:先处理所有完整托盘
+//        /**
+//         * 处理完整托盘
+//         * 先分配完整托盘
+//         */
 //        foreach ($data['products'] as $product) {
-//            // 8.1 计算托盘配置
+//            // 6.1 动态获取托盘配置
 //            $tray_count = $product['tray_count'] ?? 18;  // 默认18箱/托盘
-//            $box_num = $tray_count == 24 ? 4 : 3;       // 24箱时为4层,否则3层
+//
+//            // 6.2 根据托盘配置确定层数和每层箱数
+//            if ($tray_count == 18) {
+//                $box_num = 3;   // 3层
+//                $per_box = 6;   // 每层6箱
+//            } elseif ($tray_count == 24) {
+//                $box_num = 4;    // 4层
+//                $per_box = 6;    // 每层6箱
+//            } elseif ($tray_count == 36) {
+//                $box_num = 4;    // 4层
+//                $per_box = 9;    // 每层9箱
+//            } else {
+//                $this->error('不支持的托盘配置:' . $tray_count);
+//            }
+//
+//            $boxes_per_pallet = $per_box * $box_num; // 每托盘总箱数
 //            $small_num = $product['items_per_box'] ?? 20; // 每箱数量,默认20
+//            $default_layer_height = $product['default_layer_height'] ?? '1.35'; // 默认层高
 //
-//            // 8.2 处理实际数量
+//            // 6.3 计算实际发货数量(不超过剩余数量)
 //            $remaining = (int)$product['remaining_quantity'];
 //            $actual = isset($product['actual_quantity']) ?
 //                min((int)$product['actual_quantity'], $remaining) : $remaining;
 //
-//            // 8.3 计算托盘分配
-//            $boxes_per_pallet = $config['tray_num'] * $box_num; // 每托盘总箱数
+//            // 6.4 计算托盘分配
 //            $total_boxes = ceil($actual / $small_num);          // 总箱数
 //            $full_pallets = floor($total_boxes / $boxes_per_pallet); // 完整托盘数
 //            $remaining_boxes = $total_boxes % $boxes_per_pallet;     // 剩余箱数
 //
-//            // 8.4 构建产品基础信息
+//            // 6.5 构建产品基础信息
 //            $baseInfo = [
-//                'bach_ids' => $bachNum,          // 批次号
-//                'userid' => $userinfo['id'],     // 操作人ID
-//                'gdbh' => $product['gdbh'],      // 工单编号
-//                'order_ddbh' => $product['order_ddbh'], // 订单编号
-//                'cpbm' => $product['cpbm'],      // 产品编码
-//                'cpmc' => $product['cpmc'],      // 产品名称
-//                'matter_name' => $product['cpmc'], // 物料名称
-//                'remark' => $product['remark'] ?? '', // 备注
-//                'small_num' => $small_num,       // 每箱数量
-//                'unit' => $product['unit'] ?? '套', // 单位
-//                'tray_num' => $config['tray_num'], // 每层箱数
-//                'box_num' => $box_num,           // 层数
-//                'tray_count' => $tray_count,     // 总箱数/托盘
-//                'layer_height' => $product['layer_height'] ?? $config['default_layer_height'], // 层高
-//                'pallet_length' => $config['pallet_length'], // 托盘长度
-//                'pallet_width' => $config['pallet_width'],  // 托盘宽度
+//                'bach_ids' => $bachNum,
+//                'userid' => $userinfo['id'],
+//                'gdbh' => $product['gdbh'],
+//                'order_ddbh' => $product['order_ddbh'],
+//                'cpbm' => $product['cpbm'],
+//                'cpmc' => $product['cpmc'],
+//                'matter_name' => $product['cpmc'],
+//                'remark' => $product['remark'] ?? '',
+//                'small_num' => $small_num,
+//                'unit' => $product['unit'] ?? '套',
+//                'tray_num' => $per_box,
+//                'box_num' => $box_num,
+//                'tray_count' => $tray_count,
+//                'layer_height' => $product['layer_height'] ?? $default_layer_height,
+//                'pallet_length' => $product['pallet_length'] ?? '0.9',
+//                'pallet_width' => $product['pallet_width'] ?? '1.2',
 //                'bach_status' => 0,              // 状态(0:未处理)
-//                'sys_rq' => $currentDate,        // 系统日期
-//                'created_at' => $currentDateTime, // 创建时间
-//                'create_time' => $timestamp,     // 时间戳
-//                'delete_time' => ''              // 删除时间
+//                'sys_rq' => $currentDate,
+//                'created_at' => $currentDateTime,
+//                'create_time' => $timestamp,
+//                'delete_time' => ''
 //            ];
 //
-//            // 只处理完整托盘部分
+//            // 6.6 处理完整托盘
 //            if ($full_pallets > 0) {
 //                $full_qty = $full_pallets * $boxes_per_pallet * $small_num;
 //                $endNo = $currentPalletNo + $full_pallets - 1;
@@ -303,7 +315,7 @@ class QcodeAdd extends Backend{
 //                    'end_pallet_no' => $endNo
 //                ]);
 //
-//                // 生成托盘明细
+//                // 生成托盘明细记录
 //                for ($i = 0; $i < $full_pallets; $i++) {
 //                    $palletDetails[] = [
 //                        'bach_ids' => $bachNum,
@@ -320,6 +332,7 @@ class QcodeAdd extends Backend{
 //                    ];
 //                }
 //
+//                // 更新统计信息
 //                $batchStats['full_pallets'] += $full_pallets;
 //                $batchStats['total_quantity'] += $full_qty;
 //                $batchStats['total_boxes'] += $full_pallets * $boxes_per_pallet;
@@ -328,12 +341,14 @@ class QcodeAdd extends Backend{
 //            }
 //        }
 //
-//        // 第二阶段:再处理所有不完整托盘
+//        /**
+//         * 处理不完整托盘
+//         * 分配剩余不能组成完整托盘的部分
+//         */
 //        foreach ($data['products'] as $product) {
-//            //每托箱数
-//            $tray_count = $product['tray_count'];
+//            // 同上获取托盘配置
+//            $tray_count = $product['tray_count'] ?? 18;
 //
-//            //判断:每托箱数=每层箱数*每托层数
 //            if ($tray_count == 18) {
 //                $box_num = 3;
 //                $per_box = 6;
@@ -344,28 +359,21 @@ class QcodeAdd extends Backend{
 //                $box_num = 4;
 //                $per_box = 9;
 //            } else {
-//                $this->error('请联系管理员');
+//                continue; // 已在前阶段验证过,这里跳过
 //            }
-//            //每托箱数
-//            $boxes_per_pallet = $per_box * $box_num;
 //
-//            //每箱个数
-//            $small_num = $product['items_per_box'];
+//            $boxes_per_pallet = $per_box * $box_num;
+//            $small_num = $product['items_per_box'] ?? 20;
+//            $default_layer_height = $product['default_layer_height'] ?? '1.35';
 //
-//            //可发数量
 //            $remaining = (int)$product['remaining_quantity'];
-//            //实际发货数量
 //            $actual = isset($product['actual_quantity']) ?
 //                min((int)$product['actual_quantity'], $remaining) : $remaining;
 //
-//            //实际发货数量 / 每箱个数 = 总箱数
 //            $total_boxes = ceil($actual / $small_num);
-//            //多少箱 / 每托箱数 = 完整托盘数
 //            $full_pallets = floor($total_boxes / $boxes_per_pallet);
-//            // 剩余箱数
 //            $remaining_boxes = $total_boxes % $boxes_per_pallet;
 //
-//            // 构建产品基础信息(需要重新构建因为baseInfo可能在循环中被修改)
 //            $baseInfo = [
 //                'bach_ids' => $bachNum,
 //                'userid' => $userinfo['id'],
@@ -377,12 +385,12 @@ class QcodeAdd extends Backend{
 //                'remark' => $product['remark'] ?? '',
 //                'small_num' => $small_num,
 //                'unit' => $product['unit'] ?? '套',
-//                'tray_num' => $config['tray_num'],
+//                'tray_num' => $per_box,
 //                'box_num' => $box_num,
 //                'tray_count' => $tray_count,
-//                'layer_height' => $product['layer_height'] ?? $config['default_layer_height'],
-//                'pallet_length' => $config['pallet_length'],
-//                'pallet_width' => $config['pallet_width'],
+//                'layer_height' => $product['layer_height'] ?? $default_layer_height,
+//                'pallet_length' => $product['pallet_length'] ?? '0.9',
+//                'pallet_width' => $product['pallet_width'] ?? '1.2',
 //                'bach_status' => 0,
 //                'sys_rq' => $currentDate,
 //                'created_at' => $currentDateTime,
@@ -390,7 +398,7 @@ class QcodeAdd extends Backend{
 //                'delete_time' => ''
 //            ];
 //
-//            // 处理不完整托盘部分
+//            // 处理不完整托盘
 //            if ($remaining_boxes > 0) {
 //                $partial_qty = $remaining_boxes * $small_num;
 //
@@ -412,12 +420,13 @@ class QcodeAdd extends Backend{
 //                    'pallet_type' => 'partial',
 //                    'quantity' => $partial_qty,
 //                    'box_count' => $remaining_boxes,
-//                    'layer_count' => ceil($remaining_boxes / $config['tray_num']),
+//                    'layer_count' => ceil($remaining_boxes / $per_box),
 //                    'bach_status' => 0,
 //                    'created_at' => $currentDateTime,
 //                    'delete_time' => ''
 //                ];
 //
+//                // 更新统计信息
 //                $batchStats['partial_pallets']++;
 //                $batchStats['total_quantity'] += $partial_qty;
 //                $batchStats['total_boxes'] += $remaining_boxes;
@@ -426,7 +435,6 @@ class QcodeAdd extends Backend{
 //            }
 //        }
 //
-//        // 9. 构建批次汇总数据
 //        $summaryData = [
 //            'bach_ids' => $bachNum,
 //            'userid' => $userinfo['id'],
@@ -442,199 +450,157 @@ class QcodeAdd extends Backend{
 //            'create_time' => $timestamp,
 //            'delete_time' => ''
 //        ];
-//die;
-//        // 10. 保存所有数据
-//        $mongo->name($collection)->insertAll($productDetails);
-//        $mongo->name($bachdetails)->insertAll($palletDetails);
-//        $mongo->name($bachsummary)->insert($summaryData);
 //
-//        // 11. 更新库存记录
-//        foreach ($data['products'] as $product) {
-//            $where = [
-//                'gdbh' => $product['gdbh'],
-//                'order_ddbh' => $product['order_ddbh'],
-//                'cpmc' => $product['cpmc'],
-//            ];
 //
-//            $actual = (int)($product['actual_quantity'] ?? 0);
-//            $remaining = (int)$product['remaining_quantity'];
+//            //  写入产品主表
+//            $mongo->name($collection)->insertAll($productDetails);
 //
-//            // 处理MongoDB查询结果
-//            $existing = $mongo->name('inventory_summary')->where($where)->find();
+//            // 写入托盘明细表
+//            $mongo->name($bachdetails)->insertAll($palletDetails);
 //
-//            if ($existing) {
-//                // 转换为数组处理
-//                if (is_object($existing)) {
-//                    $existing = (array)$existing;
-//                }
+//            //  写入批次汇总表
+//            $mongo->name($bachsummary)->insert($summaryData);
 //
-//                // 处理多结果情况
-//                if (isset($existing[0])) {
-//                    $existing = $existing[0];
-//                }
 //
-//                // 安全获取字段值
-//                $current_chu = (int)($existing['total_chu_quantity'] ?? 0);
-//                $current_remain = (int)($existing['remaining_quantity'] ?? 0);
+//            foreach ($data['products'] as $product) {
+//                $where = [
+//                    'gdbh' => $product['gdbh'],
+//                    'order_ddbh' => $product['order_ddbh'],
+//                    'cpmc' => $product['cpmc'],
+//                ];
 //
-//                $mongo->name('inventory_summary')
-//                    ->where($where)
-//                    ->update([
-//                        'total_chu_quantity' => $current_chu + $actual,
-//                        'remaining_quantity' => $current_remain - $actual,
-//                        'updated_at' => $currentDateTime,
+//                $actual = (int)($product['actual_quantity'] ?? 0);
+//                $remaining = (int)$product['remaining_quantity'];
+//
+//                // 查询现有库存记录
+//                $existing = $mongo->name('inventory_summary')->where($where)->find();
+//
+//                if ($existing) {
+//                    // 处理查询结果
+//                    if (is_object($existing)) {
+//                        $existing = (array)$existing;
+//                    }
+//                    if (isset($existing[0])) {
+//                        $existing = $existing[0];
+//                    }
+//
+//                    // 更新库存
+//                    $mongo->name('inventory_summary')
+//                        ->where($where)
+//                        ->update([
+//                            'total_chu_quantity' => ($existing['total_chu_quantity'] ?? 0) + $actual,
+//                            'remaining_quantity' => ($existing['remaining_quantity'] ?? 0) - $actual,
+//                            'updated_at' => $currentDateTime,
+//                        ]);
+//                } else {
+//                    // 新增库存记录
+//                    $mongo->name('inventory_summary')->insert([
+//                        'gdbh' => $product['gdbh'],
+//                        'order_ddbh' => $product['order_ddbh'],
+//                        'cpbm' => $product['cpbm'],
+//                        'cpmc' => $product['cpmc'],
+//                        'total_ru_quantity' => $remaining,
+//                        'total_chu_quantity' => $actual,
+//                        'remaining_quantity' => $remaining - $actual,
+//                        'created_at' => $currentDateTime,
+//                        'company' => $data['company_name'] ?? '',
 //                    ]);
-//            } else {
-//                // 新记录
-//                $mongo->name('inventory_summary')->insert([
+//                }
+//
+//                // 添加库存记录
+//                $mongo->name('inventory_records')->insert([
 //                    'gdbh' => $product['gdbh'],
 //                    'order_ddbh' => $product['order_ddbh'],
 //                    'cpbm' => $product['cpbm'],
 //                    'cpmc' => $product['cpmc'],
-//                    'total_ru_quantity' => $remaining,
-//                    'total_chu_quantity' => $actual,
+//                    'operation_type' => 'outbound',
+//                    'quantity' => $actual,
 //                    'remaining_quantity' => $remaining - $actual,
+//                    'operator' => $userinfo['id'],
 //                    'created_at' => $currentDateTime,
+//                    'batch_number' => $bachNum,
 //                    'company' => $data['company_name'] ?? '',
 //                ]);
 //            }
-//
-//            // 插入库存流水记录
-//            $mongo->name('inventory_records')->insert([
-//                'gdbh' => $product['gdbh'],
-//                'order_ddbh' => $product['order_ddbh'],
-//                'cpbm' => $product['cpbm'],
-//                'cpmc' => $product['cpmc'],
-//                'total_ru_quantity' => $remaining,
-//                'total_chu_quantity' => $actual,
-//                'remaining_quantity' => $remaining - $actual,
-//                'created_at' => $currentDateTime,
-//                'company' => $data['company_name'] ?? '',
-//            ]);
-//        }
-//
-//        $this->success('批次创建成功');
+//            $this->success('批次创建成功');
 //    }
 
-
-    /**
-     * 添加批次功能
-     *
-     * 功能说明:
-     * 1. 处理AJAX请求,创建产品批次
-     * 2. 自动计算托盘分配(完整托盘和不完整托盘)
-     * 3. 生成批次号和相关统计信息
-     * 4. 更新库存记录
-     * 5. 支持多种托盘配置(18箱/24箱/36箱)
-     *
-     * 数据流向:
-     * 前端提交 -> 验证 -> 计算分配 -> 生成记录 -> 更新库存 -> 返回结果
-     */
     public function add_bach()
     {
-        // ==================== 1. 请求验证阶段 ====================
-
-        // 1.1 验证必须是AJAX请求
         if (!$this->request->isAjax()) {
             $this->error('非法请求,必须使用AJAX方式提交');
         }
 
-        // 1.2 获取并解析输入数据
-        $data = input('row'); // 获取原始数据
+        $data = input('row');
         if (empty($data)) {
             $this->error('请求参数不能为空');
         }
 
-        // 1.3 解析JSON数据
         $data = json_decode($data, true);
         if (json_last_error() !== JSON_ERROR_NONE) {
             $this->error('JSON数据解析失败:' . json_last_error_msg());
         }
 
-        // 1.4 验证产品数据是否存在
         if (empty($data['products']) || !is_array($data['products'])) {
             $this->error('产品数据不能为空且必须是数组');
         }
 
-        // ==================== 2. 用户会话验证 ====================
-
         $userinfo = Session::get('admin');
         if (empty($userinfo) || !isset($userinfo['company'])) {
             $this->error('获取用户信息失败,请重新登录');
         }
 
-        // ==================== 3. 数据库准备 ====================
-
-        // 3.1 连接MongoDB
         $mongo = \think\Db::connect('mongodb');
-
-        // 3.2 动态生成集合名称(基于公司名称)
-        $collection = $userinfo['company'] . '_qcode_bach';       // 主表
-        $bachdetails = $userinfo['company'] . '_qcode_bachdetails'; // 托盘明细表
-        $bachsummary = $userinfo['company'] . '_qcode_bachsummary'; // 批次汇总表
-
-        // ==================== 4. 生成批次信息 ====================
+        $collection = $userinfo['company'] . '_qcode_bach';
+        $bachdetails = $userinfo['company'] . '_qcode_bachdetails';
+        $bachsummary = $userinfo['company'] . '_qcode_bachsummary';
 
         $currentDate = date('Y-m-d');
         $currentDateTime = date('Y-m-d H:i:s');
         $timestamp = time();
-        // 批次号规则:BACH + 年月日时分秒 + 4位随机数
         $bachNum = 'BACH' . date('YmdHis') . mt_rand(1000, 9999);
 
-        // ==================== 5. 初始化统计容器 ====================
-
         $batchStats = [
-            'total_quantity' => 0,      // 总产品数量
-            'total_boxes' => 0,         // 总箱数
-            'total_pallets' => 0,       // 总托盘数
-            'full_pallets' => 0,        // 完整托盘数
-            'partial_pallets' => 0,     // 不完整托盘数
-            'product_varieties' => count($data['products']) // 产品种类数
+            'total_quantity' => 0,
+            'total_boxes' => 0,
+            'total_pallets' => 0,
+            'full_pallets' => 0,
+            'partial_pallets' => 0,
+            'product_varieties' => count($data['products'])
         ];
 
-        // ==================== 6. 处理产品数据 ====================
+        $productDetails = [];
+        $palletDetails = [];
+        $currentPalletNo = 1;
 
-        $productDetails = [];  // 产品主表数据
-        $palletDetails = [];   // 托盘明细数据
-        $currentPalletNo = 1;  // 托盘编号计数器
-
-        /**
-         * 第一阶段:处理完整托盘
-         * 逻辑:先分配完整托盘,确保托盘利用率最大化
-         */
         foreach ($data['products'] as $product) {
-            // 6.1 动态获取托盘配置
-            $tray_count = $product['tray_count'] ?? 18;  // 默认18箱/托盘
+            $tray_count = $product['tray_count'] ?? 18;
 
-            // 6.2 根据托盘配置确定层数和每层箱数
             if ($tray_count == 18) {
-                $box_num = 3;   // 3层
-                $per_box = 6;   // 每层6箱
+                $box_num = 3;
+                $per_box = 6;
             } elseif ($tray_count == 24) {
-                $box_num = 4;    // 4层
-                $per_box = 6;    // 每层6箱
+                $box_num = 4;
+                $per_box = 6;
             } elseif ($tray_count == 36) {
-                $box_num = 4;    // 4层
-                $per_box = 9;    // 每层9箱
+                $box_num = 4;
+                $per_box = 9;
             } else {
                 $this->error('不支持的托盘配置:' . $tray_count);
             }
 
-            $boxes_per_pallet = $per_box * $box_num; // 每托盘总箱数
-            $small_num = $product['items_per_box'] ?? 20; // 每箱数量,默认20
-            $default_layer_height = $product['default_layer_height'] ?? '1.35'; // 默认层高
+            $boxes_per_pallet = $per_box * $box_num;
+            $small_num = $product['items_per_box'] ?? 20;
+            $default_layer_height = $product['default_layer_height'] ?? '1.35';
 
-            // 6.3 计算实际发货数量(不超过剩余数量)
             $remaining = (int)$product['remaining_quantity'];
-            $actual = isset($product['actual_quantity']) ?
-                min((int)$product['actual_quantity'], $remaining) : $remaining;
+            $actual = isset($product['actual_quantity']) ? min((int)$product['actual_quantity'], $remaining) : $remaining;
 
-            // 6.4 计算托盘分配
-            $total_boxes = ceil($actual / $small_num);          // 总箱数
-            $full_pallets = floor($total_boxes / $boxes_per_pallet); // 完整托盘数
-            $remaining_boxes = $total_boxes % $boxes_per_pallet;     // 剩余箱数
+            $full_pallets = floor($actual / ($boxes_per_pallet * $small_num));
+            $full_qty = $full_pallets * $boxes_per_pallet * $small_num;
+            $partial_qty = $actual - $full_qty;
+            $remaining_boxes = ceil($partial_qty / $small_num);
 
-            // 6.5 构建产品基础信息
             $baseInfo = [
                 'bach_ids' => $bachNum,
                 'userid' => $userinfo['id'],
@@ -652,16 +618,14 @@ class QcodeAdd extends Backend{
                 'layer_height' => $product['layer_height'] ?? $default_layer_height,
                 'pallet_length' => $product['pallet_length'] ?? '0.9',
                 'pallet_width' => $product['pallet_width'] ?? '1.2',
-                'bach_status' => 0,              // 状态(0:未处理)
+                'bach_status' => 0,
                 'sys_rq' => $currentDate,
                 'created_at' => $currentDateTime,
                 'create_time' => $timestamp,
                 'delete_time' => ''
             ];
 
-            // 6.6 处理完整托盘
             if ($full_pallets > 0) {
-                $full_qty = $full_pallets * $boxes_per_pallet * $small_num;
                 $endNo = $currentPalletNo + $full_pallets - 1;
 
                 $productDetails[] = array_merge($baseInfo, [
@@ -674,93 +638,33 @@ class QcodeAdd extends Backend{
                     'end_pallet_no' => $endNo
                 ]);
 
-                // 生成托盘明细记录
                 for ($i = 0; $i < $full_pallets; $i++) {
                     $palletDetails[] = [
                         'bach_ids' => $bachNum,
+                        'code' => 'AB92' . $userinfo['printer_code'] . $product['cpbm'] . '0000000000' . date('Ymd') . $product['gdbh'] . date('Ymd') . '00000000000',
                         'product_id' => $product['gdbh'],
                         'pallet_no' => $currentPalletNo + $i,
                         'pallet_no_display' => $currentPalletNo + $i,
                         'pallet_type' => 'full',
                         'quantity' => $boxes_per_pallet * $small_num,
                         'box_count' => $boxes_per_pallet,
-                        'layer_count' => $box_num,
+                        'per_box' => $per_box,
+                        'box_num' => $box_num,
                         'bach_status' => 0,
+                        'created_time' => $currentDate,
                         'created_at' => $currentDateTime,
                         'delete_time' => ''
                     ];
                 }
 
-                // 更新统计信息
                 $batchStats['full_pallets'] += $full_pallets;
                 $batchStats['total_quantity'] += $full_qty;
                 $batchStats['total_boxes'] += $full_pallets * $boxes_per_pallet;
                 $currentPalletNo += $full_pallets;
                 $batchStats['total_pallets'] += $full_pallets;
             }
-        }
-
-        /**
-         * 第二阶段:处理不完整托盘
-         * 逻辑:分配剩余不能组成完整托盘的部分
-         */
-        foreach ($data['products'] as $product) {
-            // 同上获取托盘配置
-            $tray_count = $product['tray_count'] ?? 18;
-
-            if ($tray_count == 18) {
-                $box_num = 3;
-                $per_box = 6;
-            } elseif ($tray_count == 24) {
-                $box_num = 4;
-                $per_box = 6;
-            } elseif ($tray_count == 36) {
-                $box_num = 4;
-                $per_box = 9;
-            } else {
-                continue; // 已在前阶段验证过,这里跳过
-            }
-
-            $boxes_per_pallet = $per_box * $box_num;
-            $small_num = $product['items_per_box'] ?? 20;
-            $default_layer_height = $product['default_layer_height'] ?? '1.35';
-
-            $remaining = (int)$product['remaining_quantity'];
-            $actual = isset($product['actual_quantity']) ?
-                min((int)$product['actual_quantity'], $remaining) : $remaining;
-
-            $total_boxes = ceil($actual / $small_num);
-            $full_pallets = floor($total_boxes / $boxes_per_pallet);
-            $remaining_boxes = $total_boxes % $boxes_per_pallet;
-
-            $baseInfo = [
-                'bach_ids' => $bachNum,
-                'userid' => $userinfo['id'],
-                'gdbh' => $product['gdbh'],
-                'order_ddbh' => $product['order_ddbh'],
-                'cpbm' => $product['cpbm'],
-                'cpmc' => $product['cpmc'],
-                'matter_name' => $product['cpmc'],
-                'remark' => $product['remark'] ?? '',
-                'small_num' => $small_num,
-                'unit' => $product['unit'] ?? '套',
-                'tray_num' => $per_box,
-                'box_num' => $box_num,
-                'tray_count' => $tray_count,
-                'layer_height' => $product['layer_height'] ?? $default_layer_height,
-                'pallet_length' => $product['pallet_length'] ?? '0.9',
-                'pallet_width' => $product['pallet_width'] ?? '1.2',
-                'bach_status' => 0,
-                'sys_rq' => $currentDate,
-                'created_at' => $currentDateTime,
-                'create_time' => $timestamp,
-                'delete_time' => ''
-            ];
-
-            // 处理不完整托盘
-            if ($remaining_boxes > 0) {
-                $partial_qty = $remaining_boxes * $small_num;
 
+            if ($partial_qty > 0) {
                 $productDetails[] = array_merge($baseInfo, [
                     'actual_quantity' => $partial_qty,
                     'total_boxes' => $remaining_boxes,
@@ -773,19 +677,21 @@ class QcodeAdd extends Backend{
 
                 $palletDetails[] = [
                     'bach_ids' => $bachNum,
+                    'code' => 'AB92' . $userinfo['printer_code'] . $product['cpbm'] . '0000000000' . date('Ymd') . $product['gdbh'] . date('Ymd') . '00000000000',
                     'product_id' => $product['gdbh'],
                     'pallet_no' => $currentPalletNo,
                     'pallet_no_display' => $currentPalletNo,
                     'pallet_type' => 'partial',
                     'quantity' => $partial_qty,
                     'box_count' => $remaining_boxes,
-                    'layer_count' => ceil($remaining_boxes / $per_box),
+                    'per_box' => $per_box,
+                    'box_num' => $box_num,
                     'bach_status' => 0,
+                    'created_time' => $currentDate,
                     'created_at' => $currentDateTime,
                     'delete_time' => ''
                 ];
 
-                // 更新统计信息
                 $batchStats['partial_pallets']++;
                 $batchStats['total_quantity'] += $partial_qty;
                 $batchStats['total_boxes'] += $remaining_boxes;
@@ -794,8 +700,6 @@ class QcodeAdd extends Backend{
             }
         }
 
-        // ==================== 7. 构建批次汇总数据 ====================
-
         $summaryData = [
             'bach_ids' => $bachNum,
             'userid' => $userinfo['id'],
@@ -812,643 +716,66 @@ class QcodeAdd extends Backend{
             'delete_time' => ''
         ];
 
+        $mongo->name($collection)->insertAll($productDetails);
+        $mongo->name($bachdetails)->insertAll($palletDetails);
+        $mongo->name($bachsummary)->insert($summaryData);
 
-        // ==================== 8. 数据存储 ====================
-
-//        try {
-            // 8.1 开启事务(如果MongoDB支持)
-            // 8.2 写入产品主表
-            $mongo->name($collection)->insertAll($productDetails);
-
-            // 8.3 写入托盘明细表
-            $mongo->name($bachdetails)->insertAll($palletDetails);
-
-            // 8.4 写入批次汇总表
-            $mongo->name($bachsummary)->insert($summaryData);
-
-            // ==================== 9. 更新库存记录 ====================
-
-            foreach ($data['products'] as $product) {
-                $where = [
-                    'gdbh' => $product['gdbh'],
-                    'order_ddbh' => $product['order_ddbh'],
-                    'cpmc' => $product['cpmc'],
-                ];
-
-                $actual = (int)($product['actual_quantity'] ?? 0);
-                $remaining = (int)$product['remaining_quantity'];
-
-                // 查询现有库存记录
-                $existing = $mongo->name('inventory_summary')->where($where)->find();
+        // 库存更新部分(未改动)
+        foreach ($data['products'] as $product) {
+            $where = [
+                'gdbh' => $product['gdbh'],
+                'order_ddbh' => $product['order_ddbh'],
+                'cpmc' => $product['cpmc'],
+            ];
 
-                if ($existing) {
-                    // 处理查询结果
-                    if (is_object($existing)) {
-                        $existing = (array)$existing;
-                    }
-                    if (isset($existing[0])) {
-                        $existing = $existing[0];
-                    }
+            $actual = (int)($product['actual_quantity'] ?? 0);
+            $remaining = (int)$product['remaining_quantity'];
 
-                    // 更新库存
-                    $mongo->name('inventory_summary')
-                        ->where($where)
-                        ->update([
-                            'total_chu_quantity' => ($existing['total_chu_quantity'] ?? 0) + $actual,
-                            'remaining_quantity' => ($existing['remaining_quantity'] ?? 0) - $actual,
-                            'updated_at' => $currentDateTime,
-                        ]);
-                } else {
-                    // 新增库存记录
-                    $mongo->name('inventory_summary')->insert([
-                        'gdbh' => $product['gdbh'],
-                        'order_ddbh' => $product['order_ddbh'],
-                        'cpbm' => $product['cpbm'],
-                        'cpmc' => $product['cpmc'],
-                        'total_ru_quantity' => $remaining,
-                        'total_chu_quantity' => $actual,
-                        'remaining_quantity' => $remaining - $actual,
-                        'created_at' => $currentDateTime,
-                        'company' => $data['company_name'] ?? '',
+            $existing = $mongo->name('inventory_summary')->where($where)->find();
+            if ($existing) {
+                if (is_object($existing)) $existing = (array)$existing;
+                if (isset($existing[0])) $existing = $existing[0];
+
+                $mongo->name('inventory_summary')
+                    ->where($where)
+                    ->update([
+                        'total_chu_quantity' => ($existing['total_chu_quantity'] ?? 0) + $actual,
+                        'remaining_quantity' => ($existing['remaining_quantity'] ?? 0) - $actual,
+                        'updated_at' => $currentDateTime,
                     ]);
-                }
-
-                // 添加库存流水记录
-                $mongo->name('inventory_records')->insert([
+            } else {
+                $mongo->name('inventory_summary')->insert([
                     'gdbh' => $product['gdbh'],
                     'order_ddbh' => $product['order_ddbh'],
                     'cpbm' => $product['cpbm'],
                     'cpmc' => $product['cpmc'],
-                    'operation_type' => 'outbound',
-                    'quantity' => $actual,
+                    'total_ru_quantity' => $remaining,
+                    'total_chu_quantity' => $actual,
                     'remaining_quantity' => $remaining - $actual,
-                    'operator' => $userinfo['id'],
                     'created_at' => $currentDateTime,
-                    'batch_number' => $bachNum,
                     'company' => $data['company_name'] ?? '',
                 ]);
             }
 
-            // 返回成功响应
-            $this->success('批次创建成功');
+            $mongo->name('inventory_records')->insert([
+                'gdbh' => $product['gdbh'],
+                'order_ddbh' => $product['order_ddbh'],
+                'cpbm' => $product['cpbm'],
+                'cpmc' => $product['cpmc'],
+                'operation_type' => 'outbound',
+                'total_ru_quantity' => $remaining,
+                'total_chu_quantity' => $actual,
+                'remaining_quantity' => $remaining - $actual,
+                'operator' => $userinfo['id'],
+                'created_at' => $currentDateTime,
+                'batch_number' => $bachNum,
+                'company' => $data['company_name'] ?? '',
+            ]);
+        }
 
-//        } catch (\Exception $e) {
-//             错误处理
-//            $this->error('批次创建失败:' . $e->getMessage());
-//        }
+        $this->success('批次创建成功');
     }
 
-//    public function add_bach()
-//    {
-//        // 1. 请求验证部分
-//        if (!$this->request->isAjax()) {
-//            $this->error('请求必须为AJAX');
-//        }
-//
-//        $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('产品数据不能为空');
-//        }
-//
-//        // 2. 用户验证
-//        $userinfo = Session::get('admin');
-//        if (empty($userinfo) || !isset($userinfo['company'])) {
-//            $this->error('获取用户信息失败,请重新登录');
-//        }
-//
-//        // 3. 数据库连接
-//        $mongo = \think\Db::connect('mongodb');
-//        $collection = $userinfo['company'] . '_qcode_bach';      // 产品主表
-//        $bachdetails = $userinfo['company'] . '_qcode_bachdetails'; // 托盘明细表
-//        $bachsummary = $userinfo['company'] . '_qcode_bachsummary'; // 批次汇总表
-//
-//        // 4. 生成批次信息
-//        $currentDate = date('Y-m-d');
-//        $currentDateTime = date('Y-m-d H:i:s');
-//        $timestamp = time();
-//        $bachNum = 'BACH' . date('YmdHis') . mt_rand(1000, 9999);
-//
-//        // 5. 托盘配置
-//        $config = [
-//            'tray_num' => 6,       // 每层6箱
-//            'small_num' => 20,     // 每箱20个
-//            'pallet_length' => '0.9',
-//            'pallet_width' => '1.2',
-//            'default_layer_height' => '1.35'
-//        ];
-//
-//        // 6. 初始化数据容器
-//        $fullPalletsData = [];  // 完整托盘数据
-//        $partialPalletsData = []; // 不完整托盘数据
-//        $palletDetails = [];    // 托盘明细数据
-//        $batchStats = [
-//            'total_quantity' => 0,    // 总产品数量
-//            'total_boxes' => 0,       // 总箱数
-//            'total_pallets' => 0,     // 总托盘数
-//            'full_pallets' => 0,      // 完整托盘数
-//            'partial_pallets' => 0,   // 不完整托盘数
-//            'product_varieties' => count($data['products']) // 产品种类数
-//        ];
-//
-//        $currentPalletNo = 1; // 全局托盘计数器
-//
-//        // 7. 第一阶段:处理所有完整托盘
-//        foreach ($data['products'] as $product) {
-//            // 7.1 计算托盘配置
-//            $tray_count = isset($product['tray_count']) ? (int)$product['tray_count'] : 18;
-//            $box_num = $tray_count == 24 ? 4 : 3;
-//
-//            // 7.2 处理数量 - 确保不超过剩余数量
-//            $remaining_quantity = (int)$product['remaining_quantity'];
-//            $actual_quantity = isset($product['actual_quantity']) ?
-//                min((int)$product['actual_quantity'], $remaining_quantity) :
-//                $remaining_quantity;
-//
-//            // 7.3 计算托盘分配
-//            $boxes_per_pallet = $config['tray_num'] * $box_num;
-//            $total_boxes = ceil($actual_quantity / $config['small_num']);
-//            $full_pallets = floor($total_boxes / $boxes_per_pallet);
-//            $remaining_boxes = $total_boxes % $boxes_per_pallet;
-//
-//            // 7.4 产品基础信息
-//            $baseProductInfo = [
-//                'bach_ids' => $bachNum,
-//                'userid' => $userinfo['id'],
-//                'gdbh' => $product['gdbh'],
-//                'order_ddbh' => $product['order_ddbh'],
-//                'cpbm' => $product['cpbm'],
-//                'cpmc' => $product['cpmc'],
-//                'matter_name' => $product['cpmc'],
-//                'remark' => $product['remark'] ?? '',
-//                'small_num' => $config['small_num'],
-//                'tray_num' => $config['tray_num'],
-//                'box_num' => $box_num,
-//                'tray_count' => $tray_count,
-//                'layer_height' => $product['layer_height'] ?? $config['default_layer_height'],
-//                'pallet_length' => $config['pallet_length'],
-//                'pallet_width' => $config['pallet_width'],
-//                'bach_status' => 0,
-//                'sys_rq' => $currentDate,
-//                'created_at' => $currentDateTime,
-//                'create_time' => $timestamp,
-//                'delete_time' => ''
-//            ];
-//
-//            // 7.5 处理完整托盘
-//            if ($full_pallets > 0) {
-//                $full_quantity = $full_pallets * $boxes_per_pallet * $config['small_num'];
-//                $endPalletNo = $currentPalletNo + $full_pallets - 1;
-//
-//                $fullPalletsData[] = [
-//                    'product_info' => array_merge($baseProductInfo, [
-//                        'actual_quantity' => $full_quantity,
-//                        'total_boxes' => $full_pallets * $boxes_per_pallet,
-//                        'pallet_count' => $full_pallets,
-//                        'pallet_type' => 'full',
-//                        'pallet_range' => $currentPalletNo . '-' . $endPalletNo,
-//                        'start_pallet_no' => $currentPalletNo,
-//                        'end_pallet_no' => $endPalletNo
-//                    ]),
-//                    'pallet_count' => $full_pallets,
-//                    'start_no' => $currentPalletNo,
-//                    'boxes_per_pallet' => $boxes_per_pallet,
-//                    'box_num' => $box_num
-//                ];
-//
-//                $batchStats['full_pallets'] += $full_pallets;
-//                $batchStats['total_quantity'] += $full_quantity;
-//                $batchStats['total_boxes'] += $full_pallets * $boxes_per_pallet;
-//                $currentPalletNo += $full_pallets;
-//                $batchStats['total_pallets'] += $full_pallets;
-//            }
-//        }
-//
-//        // 8. 第二阶段:处理所有不完整托盘
-//        foreach ($data['products'] as $product) {
-//            // 8.1 计算托盘配置
-//            $tray_count = isset($product['tray_count']) ? (int)$product['tray_count'] : 18;
-//            $box_num = $tray_count == 24 ? 4 : 3;
-//
-//            // 8.2 处理数量 - 确保不超过剩余数量
-//            $remaining_quantity = (int)$product['remaining_quantity'];
-//            $actual_quantity = isset($product['actual_quantity']) ?
-//                min((int)$product['actual_quantity'], $remaining_quantity) :
-//                $remaining_quantity;
-//
-//            // 8.3 计算托盘分配
-//            $boxes_per_pallet = $config['tray_num'] * $box_num;
-//            $total_boxes = ceil($actual_quantity / $config['small_num']);
-//            $full_pallets = floor($total_boxes / $boxes_per_pallet);
-//            $remaining_boxes = $total_boxes % $boxes_per_pallet;
-//
-//            // 8.4 产品基础信息
-//            $baseProductInfo = [
-//                'bach_ids' => $bachNum,
-//                'userid' => $userinfo['id'],
-//                'gdbh' => $product['gdbh'],
-//                'order_ddbh' => $product['order_ddbh'],
-//                'cpbm' => $product['cpbm'],
-//                'cpmc' => $product['cpmc'],
-//                'matter_name' => $product['cpmc'],
-//                'remark' => $product['remark'] ?? '',
-//                'small_num' => $config['small_num'],
-//                'tray_num' => $config['tray_num'],
-//                'box_num' => $box_num,
-//                'tray_count' => $tray_count,
-//                'layer_height' => $product['layer_height'] ?? $config['default_layer_height'],
-//                'pallet_length' => $config['pallet_length'],
-//                'pallet_width' => $config['pallet_width'],
-//                'bach_status' => 0,
-//                'sys_rq' => $currentDate,
-//                'created_at' => $currentDateTime,
-//                'create_time' => $timestamp,
-//                'delete_time' => ''
-//            ];
-//
-//            // 8.5 处理不完整托盘
-//            if ($remaining_boxes > 0) {
-//                // 计算完整托盘已经处理的数量
-//                $full_quantity = $full_pallets * $boxes_per_pallet * $config['small_num'];
-//                // 确保不完整托盘数量不超过剩余数量
-//                $partial_quantity = min($remaining_boxes * $config['small_num'], $actual_quantity - $full_quantity);
-//
-//                $partialPalletsData[] = [
-//                    'product_info' => array_merge($baseProductInfo, [
-//                        'actual_quantity' => $partial_quantity,
-//                        'total_boxes' => $remaining_boxes,
-//                        'pallet_count' => 1,
-//                        'pallet_type' => 'partial',
-//                        'pallet_range' => (string)$currentPalletNo,
-//                        'start_pallet_no' => $currentPalletNo,
-//                        'end_pallet_no' => $currentPalletNo
-//                    ]),
-//                    'pallet_count' => 1,
-//                    'start_no' => $currentPalletNo,
-//                    'remaining_boxes' => $remaining_boxes
-//                ];
-//
-//                $batchStats['partial_pallets']++;
-//                $batchStats['total_quantity'] += $partial_quantity;
-//                $batchStats['total_boxes'] += $remaining_boxes;
-//                $currentPalletNo++;
-//                $batchStats['total_pallets']++;
-//            }
-//        }
-//
-//        // 9. 验证总数是否正确
-//        $expected_total = array_sum(array_map(function($product) {
-//            return isset($product['actual_quantity']) ?
-//                min((int)$product['actual_quantity'], (int)$product['remaining_quantity']) :
-//                (int)$product['remaining_quantity'];
-//        }, $data['products']));
-//
-//        if ($batchStats['total_quantity'] != $expected_total) {
-//            $this->error('计算数量不一致,预期: '.$expected_total.',实际: '.$batchStats['total_quantity']);
-//        }
-//
-//        // 10. 合并所有托盘数据(完整托盘在前,不完整托盘在后)
-//        $allPalletData = array_merge($fullPalletsData, $partialPalletsData);
-//
-//        // 11. 生成最终的产品主表数据和托盘明细数据
-//        $productDetails = [];
-//        $palletDetails = [];
-//        $currentPalletNo = 1; // 重新开始计数
-//
-//        foreach ($allPalletData as $pallet) {
-//            if (isset($pallet['boxes_per_pallet'])) {
-//                // 完整托盘
-//                $endPalletNo = $currentPalletNo + $pallet['pallet_count'] - 1;
-//
-//                $productDetails[] = array_merge($pallet['product_info'], [
-//                    'pallet_range' => $currentPalletNo . '-' . $endPalletNo,
-//                    'start_pallet_no' => $currentPalletNo,
-//                    'end_pallet_no' => $endPalletNo
-//                ]);
-//
-//                // 生成托盘明细
-//                for ($i = 0; $i < $pallet['pallet_count']; $i++) {
-//                    $palletDetails[] = [
-//                        'bach_ids' => $bachNum,
-//                        'product_id' => $pallet['product_info']['gdbh'],
-//                        'pallet_no' => $currentPalletNo + $i,
-//                        'pallet_no_display' => $currentPalletNo + $i,
-//                        'pallet_type' => 'full',
-//                        'quantity' => $pallet['boxes_per_pallet'] * $config['small_num'],
-//                        'box_count' => $pallet['boxes_per_pallet'],
-//                        'layer_count' => $pallet['box_num'],
-//                        'bach_status' => 0,
-//                        'created_at' => $currentDateTime,
-//                        'delete_time' => ''
-//                    ];
-//                }
-//
-//                $currentPalletNo += $pallet['pallet_count'];
-//            } else {
-//                // 不完整托盘
-//                $productDetails[] = array_merge($pallet['product_info'], [
-//                    'pallet_range' => (string)$currentPalletNo,
-//                    'start_pallet_no' => $currentPalletNo,
-//                    'end_pallet_no' => $currentPalletNo
-//                ]);
-//
-//                $palletDetails[] = [
-//                    'bach_ids' => $bachNum,
-//                    'product_id' => $pallet['product_info']['gdbh'],
-//                    'pallet_no' => $currentPalletNo,
-//                    'pallet_no_display' => $currentPalletNo,
-//                    'pallet_type' => 'partial',
-//                    'quantity' => $pallet['product_info']['actual_quantity'],
-//                    'box_count' => $pallet['product_info']['total_boxes'],
-//                    'layer_count' => ceil($pallet['product_info']['total_boxes'] / $config['tray_num']),
-//                    'bach_status' => 0,
-//                    'created_at' => $currentDateTime,
-//                    'delete_time' => ''
-//                ];
-//
-//                $currentPalletNo++;
-//            }
-//        }
-//
-//        // 12. 构建批次汇总数据
-//        $summaryData = [
-//            'bach_ids' => $bachNum,             // 单据编号
-//            'userid' => $userinfo['id'],        // 用户ID
-//            'total_quantity' => $batchStats['total_quantity'], // 总发货数量
-//            'total_boxes' => $batchStats['total_boxes'],      // 总箱数
-//            'total_pallets' => $batchStats['total_pallets'],  // 总托盘数
-//            'product_count' => $batchStats['product_varieties'], // 产品数量
-//            'full_pallets' => $batchStats['full_pallets'],    // 完整托盘数
-//            'partial_pallets' => $batchStats['partial_pallets'], // 不完整托盘数
-//            'bach_status' => 0,                // 状态
-//            'sys_rq' => $currentDate,          // 日期
-//            'created_at' => $currentDateTime,  // 操作时间
-//            'create_time' => $timestamp,       // 时间戳
-//            'delete_time' => ''                // 删除时间
-//        ];
-//
-//        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);
-//        }
-//
-//        // 13. 数据入库操作
-//        try {
-//            $mongo->name($collection)->insertAll($productDetails);
-//            $mongo->name($bachdetails)->insertAll($palletDetails);
-//            $mongo->name($bachsummary)->insert($summaryData);
-//
-////            $this->success('批次创建成功', null, [
-////                'bach_num' => $bachNum,
-////                'total_quantity' => $batchStats['total_quantity'],
-////                'total_boxes' => $batchStats['total_boxes'],
-////                'total_pallets' => $batchStats['total_pallets'],
-////                'product_count' => $batchStats['product_varieties'],
-////                'pallet_range' => '1-' . ($currentPalletNo - 1)
-////            ]);
-//        } catch (\Exception $e) {
-//            $this->error('批次创建失败:' . $e->getMessage());
-//        }
-//    }
-
-
-//    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('添加成功');
-//
-//    }
-
-
-
     /**
      * 增加新批次
      */

+ 156 - 164
application/admin/controller/QcodeBach.php

@@ -87,18 +87,51 @@ class QcodeBach extends Backend
                 $where[$k] = new \MongoDB\BSON\Regex($v);
             }
 
-            $total = $this->model->name($company_id.'_'."qcode_bach")->where($where)->count();
-            $list = $this->model->name($company_id.'_'."qcode_bach")->where($where)
-                ->order($sort,$order)
-                ->limit($limit)
-                ->skip($offset)
-                ->select();
-            foreach ($list as $k=>$v) {
-                $oid = $v['_id']->jsonSerialize();
-                $list[$k]['id'] = $oid['$oid'];
+
+            $userinfo = Session::get('admin');
+            if (empty($userinfo) || !isset($userinfo['company'])) {
+                $this->error('获取用户信息失败,请重新登录');
+            }
+            $mongo = \think\Db::connect('mongodb');
+            $qcode_bach = $userinfo['company'] . '_qcode_bach';
+            $bachdetails = $userinfo['company'] . '_qcode_bachdetails';
+            $bachsummary = $userinfo['company'] . '_qcode_bachsummary';
+
+            // 查询发货单数据,admin用户可以查看所有,普通用户只能查看自己的数据
+            $query = $mongo->name('qcode_goods')->where('delete_time','');
+            if ($userinfo['username'] !== 'admin') {
+                $query = $query->where('user_id', $userinfo['id']);
             }
+            $goodsList = $query->select();
 
-            $result = array("total" => $total, "rows" => $list);
+
+            // 获取所有相关的bach_ids
+            $bachIds = [];
+            foreach ($goodsList as $v) {
+                $summary = $mongo->name($bachsummary)->where('_id', $v['qcode_bachsummary_id'])
+                    ->where('delete_time','')
+                    ->find();
+                if ($summary && !empty($summary['bach_ids'])) {
+                    $bachIds[] = $summary['bach_ids'];
+                }
+            }
+
+            // 如果有有效的bach_ids,则添加到查询条件中
+            if (!empty($bachIds)) {
+                $total = $this->model->name($qcode_bach)->where($where)->count();
+                $list = $this->model->name($qcode_bach)->where($where)
+                    ->order($sort,$order)
+                    ->limit($limit)
+                    ->skip($offset)
+                    ->select();
+                foreach ($list as $k=>$v) {
+                    $oid = $v['_id']->jsonSerialize();
+                    $list[$k]['id'] = $oid['$oid'];
+                }
+                $result = array("total" => $total, "rows" => $list);
+            } else {
+                $result = array("total" => 0, "rows" => '');
+            }
 
             return json($result);
         }
@@ -121,91 +154,77 @@ class QcodeBach extends Backend
             }
             $userInfo = Session::get('admin');
             $company_id = (int)$userInfo['company'];
-            $where = [
-//                'company_id'=>(int)$userInfo['company'],
-                'delete_time'=> ''
-            ];
-
             $req = input();
+
             if($req['filter']=='{}'){
                 $result = array("total" => 0, "rows" => []);
                 return json($result);
             }
             $req['sort'] == 'id' ? $sort = '_id' : $sort = $req['sort'];
-            $order = $req['order'];
-//            $offset = $req['offset'];
-//            $limit = $req['limit'];
-
-            // 构造模糊查询条件
-//            $regex = new MongoDB\BSON\Regex('.*abc.*', 'i');
-//            $filter = ['field' => $regex];
 
             $filter = json_decode($req['filter'], true);
             foreach ($filter as $k => $v){
                 $where[$k] = new \MongoDB\BSON\Regex($v);
             }
 
-            $db = new QcodeLarge();
-            $total = $db->name($company_id.'_'."qcode_large")->where($where)->count();
-            $list = $db->name($company_id.'_'."qcode_large")->where($where)
-                ->order($sort,$order)
-//                ->limit($limit)
-//                ->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'];
-                //设置当前托盘号
-                $list[$k]['l_flow'] = ltrim(substr($v['code'],53,6),'0');
-                //查询小件数量
-                $small_num = $qcodeSmall->name($company_id.'_'."qcode_small")
-                    ->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;
+            $mongo = \think\Db::connect('mongodb');
+            $collection = $userInfo['company'] . '_qcode_bach';
+            $bachdetails = $userInfo['company'] . '_qcode_bachdetails';
+            $bach = $mongo->name($collection)->where('_id',$filter['bach_id'])->find();
+            $total = $mongo->name($bachdetails)->where('bach_ids',$bach['bach_ids'])->count();
+            $list = $mongo->name($bachdetails)->where('bach_ids',$bach['bach_ids'])
+                ->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'];
+//                //设置当前托盘号
+//                $list[$k]['l_flow'] = ltrim(substr($v['code'],53,6),'0');
+//                //查询小件数量
+//                $small_num = $qcodeSmall->name($company_id.'_'."qcode_small")
+//                    ->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;
+//
+//            }
 
             $result = array("total" => $total, "rows" => $list);
             return json($result);
@@ -304,98 +323,71 @@ class QcodeBach extends Backend
      */
     public function print_l()
     {
+
         //设置过滤方法
         $this->request->filter(['strip_tags', 'trim']);
         $req = $this->request->param();
-        if ($this->request->isAjax()) {
 
-            $ids = $req['ids'];
-            $type = $req['type'];
-            $numn = $req['numn'];
-
-            $userInfo = Session::get('admin');
-            $company_id = (int)$userInfo['company'];
-            $qcodeLarge = new QcodeLarge();
-            $qcodeSmall = new QcodeSmall();
-            $qcodeProduct = new QcodeProduct();
-            $large = $qcodeLarge->name($company_id.'_'."qcode_large")->where('_id',$ids[0])->find();
-
-            $bach = $this->model->name($company_id.'_'."qcode_bach")->where('_id',json_decode($large,true)['bach_id'])->find();
+        $ids = $req['ids'];
+        $type = $req['type'];
+        $numn = $req['numn'];
 
-//            matter_no.order_ddbh.matter_name
-            $row = $qcodeProduct->where('product_code',json_decode($bach,true)['matter_no'])->find();
+        $userinfo = Session::get('admin');
+        if (empty($userinfo) || !isset($userinfo['company'])) {
+            $this->error('获取用户信息失败,请重新登录');
+        }
 
-            $company_name = json_decode($bach,true)['supplier_name'];
-            $product_name = json_decode($bach,true)['matter_name'];
-//            $main_unit = json_decode($row,true)['main_unit'];
-//            $sec_unit = json_decode($row,true)['sec_unit'];
-//            $proportion = json_decode($row,true)['proportion'];
-            $main_unit = '';
-            $sec_unit = json_decode($bach,true)['danwei'];
-            $proportion = json_decode($bach,true)['num'];
+        $mongo = \think\Db::connect('mongodb');
+        $collection = $userinfo['company'] . '_qcode_bach';
+        $bachdetails = $userinfo['company'] . '_qcode_bachdetails';
+        $bachsummary = $userinfo['company'] . '_qcode_bachsummary';
+
+        // 初始化数组存储所有查询结果
+        $allRows = [];
+        $alls = [];
+
+        foreach ($req['ids'] as $index => $v){
+            // 先从bachdetails集合获取原始数据
+            $detailData = $mongo->name($bachdetails)->where('_id', $v)->find();
+            if ($detailData) {
+                // 从collection集合获取cpmc字段
+                $bachData = $mongo->name($collection)->where('bach_ids', $detailData['bach_ids'])->find();
+                $bachsummaryData = $mongo->name($bachsummary)->where('bach_ids', $detailData['bach_ids'])->find();
+                // 获取ObjectId的字符串表示
+                $bachsummaryId = (string)$bachsummaryData['_id'];
+                $goods = $mongo->name("qcode_goods")->where('qcode_bachsummary_id', $bachsummaryId)->find();
+                $goodsData['order_number'] = $goods['order_number'];
+                $detailData['cpmc'] = $bachData['cpmc'];
+                $detailData['unit'] = $bachData['unit'];
+                $detailData['tray_num'] = $bachData['tray_num'];
+                $detailData['small_num'] = $bachData['small_num'];
+                $detailData['total_boxes'] = $bachData['total_boxes'];
+                $detailData['order_ddbh'] = $bachData['order_ddbh'];
+                $detailData['riqi'] = date('Y-m-d');
+
+                // 将更新后的数据添加到结果数组
+                $allRows[$index] = $detailData;
+                $alls[$index] = $goodsData;
+            }
+        }
 
-            $rows = [];
-            //查询打印大件码所需数据
-            foreach ($ids as $key=>$value){
-                $row = $qcodeLarge->name($company_id.'_'."qcode_large")->where('_id',$value)->find();
-                $row = json_decode($row,true);
-                $code = $row['code'];
-                $rows[$key]['company_name'] = $company_name;
-                $rows[$key]['product_name'] = $product_name;
-                $rows[$key]['sqrcd'] = $qcodeSmall->name($company_id.'_'."qcode_small")->where('large_id',$value)->count();
-                $rows[$key]['main_unit'] = $main_unit;
-                $rows[$key]['sec_unit'] = $sec_unit;
-                $rows[$key]['date'] = substr_replace(substr_replace('20'.substr($code,38,6), '-', 4, 0), '-', 7, 0);
-                $rows[$key]['l_flow'] =  ltrim(substr($code,53,6),'0');
-                $rows[$key]['qrcode'] = $code;
-                $rows[$key]['pCode'] = $this->qrcode($code);
-
-                //批次号特殊情况判断
-                if (substr($code,76,10)=='0000000000'){
-                    $rows[$key]['batch'] = ltrim(substr($code,66,10),'0');
-                }else{
-                    $rows[$key]['batch'] = ltrim(substr($code,66,10),'0').'、'.ltrim(substr($code,76,10),'0');
-                }
+        // 处理kes值,去掉前四位
+        if (isset($userinfo['kes'])) {
+            $userinfo['kes'] = substr($userinfo['kes'], 4);
+        }
 
-                //转换关系判断
-                if($row['l_num']===null){
-                    //走转换关系
-                    if ($proportion){
-                        $rows[$key]['num'] = $rows[$key]['sqrcd']*$proportion;
-                        $rows[$key]['num'] = floor($rows[$key]['num'] * 100) / 100;
-                    }else{
-                        $rows[$key]['num'] = '';
-                    }
-                }else if($row['l_num']==0){
-                    //判断是否是公斤
-                    if($main_unit=='公斤'){
-                        //公斤使用l_weight
-                        $rows[$key]['num'] = $row['l_weight'];
-                    }else{
-                        //不是公斤走转换关系
-                        if ($proportion){
-                            $rows[$key]['num'] = $rows[$key]['sqrcd']*$proportion;
-                            $rows[$key]['num'] = floor($rows[$key]['num'] * 100) / 100;
-                        }else{
-                            $rows[$key]['num'] = '';
-                        }
-                    }
-                }else{
-                    //箱, 使用l_num
-                    $rows[$key]['num'] = $row['l_num'];
-                }
+        // 构建返回数据
+        $data = [
+            'order_number' => $alls,
+            'userinfo' => $userinfo,
+            'type' => $type,
+            'numn' => $numn,
+            'rows' => $allRows,
+            'ids'  => $ids,
+            'count' => count($allRows)
+        ];
 
-            }
-            $data = [
-                'type'=>$type,
-                'numn'=>$numn,
-                'rows'=>$rows,
-                'ids'=>$ids,
-            ];
-            $this->success('成功','',$data);
-        }
-        $this->view->assign('ids',$req['ids']);
-        return $this->view->fetch();
+        $this->success('成功获取打印数据', '', $data);
     }
 
     /**

+ 1 - 0
application/admin/view/deliver/apply.html

@@ -171,3 +171,4 @@
     </div>
 </div>
 
+    

+ 5 - 4
application/admin/view/deliver/goods.html

@@ -3,25 +3,25 @@
     <div class="form-group">
         <label class="control-label col-xs-12 col-sm-2">输入订单号</label>
         <div class="col-xs-12 col-sm-8">
-            <input id="c-order_number" class="form-control" data-rule="required" name="order_number" type="text" >
+            <input id="c-order_number" class="form-control"  name="order_number" type="text" >
         </div>
     </div>
     <div class="form-group">
         <label class="control-label col-xs-12 col-sm-2">输入司机</label>
         <div class="col-xs-12 col-sm-8">
-            <input id="c-deliveryman" class="form-control" data-rule="required" name="deliveryman" type="text" >
+            <input id="c-deliveryman" class="form-control"  name="deliveryman" type="text" >
         </div>
     </div>
     <div class="form-group">
         <label class="control-label col-xs-12 col-sm-2">输入司机电话</label>
         <div class="col-xs-12 col-sm-8">
-            <input id="c-shr_phone" class="form-control" data-rule="required" name="shr_phone" type="text" >
+            <input id="c-shr_phone" class="form-control"  name="shr_phone" type="text" >
         </div>
     </div>
     <div class="form-group">
         <label class="control-label col-xs-12 col-sm-2">输入车牌号</label>
         <div class="col-xs-12 col-sm-8">
-            <input id="c-plate_number" class="form-control" data-rule="required" name="plate_number" type="text" >
+            <input id="c-plate_number" class="form-control"  name="plate_number" type="text" >
         </div>
     </div>
     <div class="form-group">
@@ -34,6 +34,7 @@
         <label class="control-label col-xs-12 col-sm-1"></label>
         <div class="col-xs-12 col-sm-2">
             <button type="submit" class="btn btn-success" id="apply_btn">提交</button>
+            <button type="submit" class="btn btn-primary" id="Replication">复制发货信息</button>
         </div>
     </div>
 </form>

+ 33 - 14
application/admin/view/qcode_add/index.html

@@ -274,6 +274,8 @@
                     <td colSpan="3">合计</td>
                     <td></td>
                     <td></td>
+                    <td></td>
+                    <td></td>
                     <td id="totalQuantity">0</td>
                     <td colSpan="2"></td>
                 </tr>
@@ -412,12 +414,14 @@
                     </datalist>
                 </td>
                 <td>
-                    <select class="unit-select" data-index="${index}">
-                        <option value="套" ${product.unit === '套' ? 'selected' : ''}>套</option>
-                        <option value="张" ${product.unit === '张' ? 'selected' : ''}>张</option>
-                        <option value="个" ${product.unit === '个' ? 'selected' : ''}>个</option>
-                    </select>
-                </td>
+                        <select class="unit-select" data-index="${index}">
+                            <option value="套" ${product.unit === '套' ? 'selected' : ''}>套</option>
+                            <option value="张" ${product.unit === '张' ? 'selected' : ''}>张</option>
+                            <option value="个" ${product.unit === '个' ? 'selected' : ''}>个</option>
+                            <option value="托" ${product.unit === '托' ? 'selected' : ''}>托</option>
+                            <option value="卷" ${product.unit === '卷' ? 'selected' : ''}>卷</option>
+                        </select>
+                    </td>
                 <td>
                     <select class="tray-count-select" data-index="${index}">
                         <option value="18" ${product.tray_count == 18 ? 'selected' : ''}>18</option>
@@ -584,6 +588,16 @@
                     <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>
+                        <select name="unit" class="form-control" required>
+                            <option value="套" selected>套</option>
+                            <option value="张">张</option>
+                            <option value="个">个</option>
+                            <option value="托">托</option>
+                            <option value="卷">卷</option>
+                        </select>
+                    </td>
+                    <td><input type="text" name="remark" class="form-control" /></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>
@@ -609,6 +623,8 @@
                                     <th>成品编码</th>
                                     <th>成品名称</th>
                                     <th>入库数</th>
+                                    <th>单位</th>
+                                    <th>备注</th>
                                     <th>操作</th>
                                 </tr>
                             </thead>
@@ -637,14 +653,19 @@
                         const rowData = {};
                         let rowValid = true;
 
-                        $(this).find('[required]').each(function () {
+                        // 获取所有输入字段和select字段,包括必填和非必填
+                        $(this).find('input, select').each(function () {
+                            const name = $(this).attr('name');
                             const val = $(this).val().trim();
-                            if (!val) {
+
+                            // 对必填字段进行验证
+                            if ($(this).prop('required') && !val) {
                                 layer.tips('此项为必填项', $(this), {tips: [1, '#FF5722']});
                                 isValid = rowValid = false;
                                 return false;
                             }
-                            rowData[$(this).attr('name')] = val;
+
+                            rowData[name] = val;
                         });
 
                         if (rowValid) {
@@ -653,7 +674,6 @@
                             rowData.tray_count = 18;
                             rowData.layer_height = '1.35';
                             rowData.items_per_box = '20';
-                            rowData.unit = '个';
                             rowData.isNew = true;
                             newProducts.push(rowData);
                         }
@@ -678,7 +698,7 @@
                                 items_per_box: product.items_per_box,
                                 unit: product.unit,
                                 isNew: true,
-                                remark: ''
+                                remark: product.remark || ''
                             });
                         }
                     });
@@ -794,12 +814,11 @@
                 type: 'POST',
                 data: {row: JSON.stringify(postData)},
             }, function (data, res) {
-                layer.close(loadingIndex);
+                // layer.close(loadingIndex);
+                console.log(res.code);
                 if (res.code == 1) {
                     window.location.reload();
                     Backend.api.addtabs('/deliver/index');
-                    // layer.msg('保存成功', {icon: 1});
-                    // window.location.reload();
                 } else {
                     layer.msg(res.msg || '保存失败', {icon: 2});
                 }

+ 8 - 8
application/admin/view/qcode_bach/index.html

@@ -80,17 +80,17 @@
                             <button style="background-color: #f4f4f4;color: #f4f4f4;border-color: #ddd">
                                 <a href="javascript:;" style="color: black"
                                    id="print_l"
-                                   class="btn btn-defaults btn-disabled disabled {:$auth->check('qcode_bach/print_l')?'':'hide'}"
+                                   class="btn btn-defaults {:$auth->check('qcode_bach/print_l')?'':'hide'}"
                                    title="自动打码(大件)">
                                     <i class="fa"></i> 自动打码(大件)</a>
                             </button>
-                            <button style="background-color: #f4f4f4;color: #f4f4f4;border-color: #ddd">
-                                <a href="javascript:;" style="color: black"
-                                   id="print_s"
-                                   class="btn btn-defaults btn-disabled disabled {:$auth->check('qcode_bach/print_s')?'':'hide'}"
-                                   title="自动打码(小件)">
-                                    <i class="fa"></i> 自动打码(小件)</a>
-                            </button>
+<!--                            <button style="background-color: #f4f4f4;color: #f4f4f4;border-color: #ddd">-->
+<!--                                <a href="javascript:;" style="color: black"-->
+<!--                                   id="print_s"-->
+<!--                                   class="btn btn-defaults btn-disabled disabled {:$auth->check('qcode_bach/print_s')?'':'hide'}"-->
+<!--                                   title="自动打码(小件)">-->
+<!--                                    <i class="fa"></i> 自动打码(小件)</a>-->
+<!--                            </button>-->
                         </div>
 
                         <!-- 表格滚动区域 -->

File diff suppressed because it is too large
+ 579 - 382
public/assets/js/backend/deliver.js


+ 119 - 423
public/assets/js/backend/qcode_bach.js

@@ -8,28 +8,30 @@ define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'LodopFuncs'], functi
             this.table.second();
 
             //大件码打印
-            function print_l(data,qrcode){
+            function print_l(data,userinfo,order_number,qrcode){
                 //打印二维码
                 var html = '<style type="text/css">' +
                     '.tg  {border-collapse:collapse;border-spacing:0;font-weight:500;}' +
-                    '.tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:black;}' +
+                    '.tg td{font-family:"Times New Roman", sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:black;}' +
                     '.tg .tg-s6z2{text-align:center;}</style>' +
                     '<div width="340px"><table class="tg" width="340px">' +
-                    '<caption style="width: 300px;">'+data.company_name+'</caption>' +
-                    '<tr><td style="width: 70px;">规格:</td><td colspan="5" style="word-break:break-all;border-color:black;">'+data.product_name+'</td>' +
-                    '<tr><td>配盘数:</td><td colspan="2">'+data.sqrcd+'</td><td>辅单位:</td><td colspan="2">'+data.sec_unit+'</td></tr>' +
-                    '<tr><td>数量:</td><td colspan="2">'+data.num+'</td><td>主单位:</td><td colspan="2">'+data.main_unit+'</td></tr>' +
-                    '<tr><td>生产日期:</td><td colspan="5">'+data.date+'</td></tr>' +
-                    '<tr><td>生产批号:</td><td colspan="5">'+data.batch+'</td></tr>' +
-                    '<tr><td colspan="6" style="word-break:break-all; border-color:black; font-size: 13px;">'+data.qrcode+'</td></table>' +
-                    '<div style="position:absolute;top: 287px;left: 30px"><img src="'+data.pCode+'" > </td></div>' +
-                    '<div style="position:absolute;top: 370px;left: 300px;width: 50px;text-align: center;"><span style="font-weight: 500;word-break:normal;font-size: 16px">大件号'+data.l_flow+'</span></div>\n' +
+                    '<caption style="width: 320px;">'+userinfo.company_name +'</caption>' +
+                    '<caption style="width: 320px;">ZHEJIANG MINONG IMP&EXP CO.'+', '+'LTD.</caption>' +
+                    '<tr><td style="width:200px;">品名'+'</br>'+'PRODUCT NAME</td><td colspan="5" style="word-break:break-all;border-color:black;">'+data.cpmc+'</td>' +
+                    '<tr><td>箱数'+'</br>'+'CASES</td><td colspan="2">'+data.total_boxes+'</td><td>生产商'+'</br>'+'PRODUCER</td><td colspan="2" style="width: 80px;">'+userinfo.kes+'</td></tr>' +
+                    '<tr><td>数量'+'</br>'+'QTY</td><td colspan="2">'+data.quantity+'</td><td>单位'+'</br>'+'UNIT</td><td colspan="2" style="width: 80px;">'+data.unit+'</td></tr>' +
+                    '<tr><td>日期'+'</br>'+'DATE</td><td colspan="5">'+data.riqi+'</td></tr>' +
+                    '<tr><td>生产批次号'+'</br>'+'BATCH NO'+'.'+'</td><td colspan="5">'+data.product_id+'</td></tr>' +
+                    '<tr><td>订单号'+'</br>'+'ORDER NO'+'.'+'</td><td colspan="5">'+order_number[0].order_number+'</td></tr>' +
+                    '<div style="position:absolute;top: 370px;left: 260px;width: 50px;text-align: center;"><span style="font-weight: 500;word-break:normal;font-size: 30px">NO'+'.'+'</br></span><span style="font-weight: 500;word-break:normal;font-size: 50px">'+data.pallet_no+'</span></div>' +
                     '</div>';
                 var printPdf = (html,qrcode) => {
                     var LODOP=getLodop();
-                    LODOP.SET_LICENSES("","152A06E8F6CBD6AC1F213ABFCB0D8604","C94CEE276DB2187AE6B65D56B3FC2848","");
+                    // LODOP.SET_LICENSES("","152A06E8F6CBD6AC1F213ABFCB0D8604","C94CEE276DB2187AE6B65D56B3FC2848","");
+                    // 设置完整的许可证信息以去除试用版提示
+                    LODOP.SET_LICENSES("浙江美浓","C94CEE276DB2187AE6B65D56B3FC2848","152A06E8F6CBD6AC1F213ABFCB0D8604","ZJMEINONG");
 
-                    LODOP.PRINT_INIT("河南中烟大件二维码打码");
+                    LODOP.PRINT_INIT("浙江美浓进出口大件二维码打码");
                     LODOP.SET_PRINT_STYLE("FontSize",16);
                     LODOP.SET_PRINT_STYLE("Bold",1);
 
@@ -37,206 +39,53 @@ define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'LodopFuncs'], functi
                     // LODOP.ADD_PRINT_HTM(15,20,350,545,html);
                     LODOP.ADD_PRINT_HTM(10,20,350,590,html);
 
-                    // LODOP.SET_PRINT_STYLEA(0,"QRCodeVersion",14);
-                    // LODOP.SET_PRINT_STYLEA(0,"QRCodeErrorLevel","M");
-                    // LODOP.ADD_PRINT_BARCODE(18,715,'27mm','27mm',"QRCode",qrcode);
+                    // 设置二维码样式并生成二维码
+                    LODOP.SET_PRINT_STYLEA(0,"QRCodeVersion",14);
+                    LODOP.SET_PRINT_STYLEA(0,"QRCodeErrorLevel","M");
+                    LODOP.ADD_PRINT_BARCODE(377,87,'50mm','50mm',"QRCode",data.code);
                     // LODOP.PRINT() // 直接打印
                     // LODOP.PRINT_DESIGN() // 设计模式
-                    if (qrcode){
+                    // if (qrcode){
                         LODOP.PREVIEW()	//打印预览
-                    }else{
-                        LODOP.PRINT() // 直接打印
-                    }
+                    // }else{
+                        // LODOP.PRINT() // 直接打印
+                    // }
 
                 }
                 printPdf(html,qrcode)
             }
 
-            //小件码打印(10mmx2.5mm)
-            function print1(data,qrcode){
-                //打印二维码
-                var html = "<style>.tg  {font-weight:500;}.tg td{font-family:宋体,楷体;font-size:10px;overflow:hidden;word-break:break-all;border-color:black;}</style> " +
-                    "<table class=\"tg\"> <tr> <td>" + data.company_name + "</td> </tr> " +
-                    "<tr> <td >规格:" + data.product_name + "</td> </tr> " +
-                    "<tr> <td>生产批号:" + data.batch + "</td> </tr> " +
-                    "<tr> <td>日期:" + data.date + "</td> </tr></table>";
-
-                var LODOP=getLodop();
-                LODOP.PRINT_INIT("小件(10mmx2.5mm)");
-                LODOP.SET_LICENSES("", "152A06E8F6CBD6AC1F213ABFCB0D8604", "C94CEE276DB2187AE6B65D56B3FC2848", "");
-                LODOP.SET_PRINT_PAGESIZE(1, 1000, 250, "CreateCustomPage");
-
-                LODOP.ADD_PRINT_HTM(15, 10, 270, 160,html);
-
-                LODOP.ADD_PRINT_TEXT(70,200,100,20,data.l_flow);
-                LODOP.SET_PRINT_STYLEA(0,"FontName","宋体");
-                LODOP.SET_PRINT_STYLEA(0,"FontSize",10);
-                LODOP.SET_PRINT_STYLEA(0,"FontColor","#000000");
-                LODOP.SET_PRINT_STYLEA(0,"Bold",1);
-
-                LODOP.SET_PRINT_STYLEA(0,"QRCodeErrorLevel","M");
-                LODOP.ADD_PRINT_BARCODE(4,280,'25mm','25mm',"QRCode",data.qrcode);
-                if (qrcode){
-                    LODOP.PREVIEW()	//打印预览
-                }else{
-                    LODOP.PRINT() // 直接打印
-                }
-
-            }
-
-            //小件码打印(10mmx1.8mm)
-            function print2(data,qrcode){
-                //打印二维码
-                var html = "<style>.tg  {border-collapse:collapse;border-spacing:0;font-weight:500;}.tg td{font-family:宋体,楷体;font-size:9px;overflow:hidden;word-break:break-all;border-color:black;}</style>" +
-                    "<table class=\"tg\"> <tr> <td>" + data.company_name + "</td> </tr> " +
-                    "<tr> <td >规格:" + data.product_name + "</td> </tr> " +
-                    "<tr> <td>生产批号:" + data.batch + "</td> </tr> " +
-                    "<tr> <td>日期:" + data.date + "</td> </tr></table>";
-
-                var LODOP=getLodop();
-                LODOP.PRINT_INIT("小件(10mmx2.5mm)");
-                LODOP.SET_LICENSES("", "152A06E8F6CBD6AC1F213ABFCB0D8604", "C94CEE276DB2187AE6B65D56B3FC2848", "");
-                LODOP.SET_PRINT_PAGESIZE(1, 1000, 180, "CreateCustomPage");
-
-                LODOP.ADD_PRINT_HTM(3, 5, 300, 160, html);
-
-                LODOP.ADD_PRINT_TEXT(50,200,100,18,data.l_flow);
-                LODOP.SET_PRINT_STYLEA(0,"FontName","宋体");
-                LODOP.SET_PRINT_STYLEA(0,"FontSize",10);
-                LODOP.SET_PRINT_STYLEA(0,"FontColor","#000000");
-                LODOP.SET_PRINT_STYLEA(0,"Bold",1);
-
-                LODOP.SET_PRINT_STYLE("QRCodeVersion",10);
-                LODOP.SET_PRINT_STYLEA(0,"QRCodeErrorLevel","M");
-                LODOP.ADD_PRINT_BARCODE(5,310,'25mm','25mm',"QRCode",data.qrcode);
-                if (qrcode){
-                    LODOP.PREVIEW()	//打印预览
-                }else{
-                    LODOP.PRINT() // 直接打印
-                }
-
-            }
-
-            //小件码打印(10mmx4mm)
-            function print3(data,qrcode){
-                //打印二维码
-                var html = "<style>" +
-                    ".tg  {border-collapse:collapse;border-spacing:0;font-weight:500;}" +
-                    ".tg td{font-family:宋体, 楷体;font-size:14px;overflow:hidden;word-break:break-all;border-color:black;}" +
-                    "</style>" +
-                    "<table class=\"tg\"> <tr> <td>" + data.company_name + "</td> </tr> " +
-                    "<tr> <td >规格:" + data.product_name + "</td> </tr> " +
-                    "<tr> <td>生产批号:" + data.batch + "</td> </tr> " +
-                    "<tr> <td>日期:" + data.date + "</td> </tr></table>";
-
-                var LODOP=getLodop();
-                LODOP.PRINT_INIT("小件(10mmx4mm)");
-                LODOP.SET_LICENSES("", "152A06E8F6CBD6AC1F213ABFCB0D8604", "C94CEE276DB2187AE6B65D56B3FC2848", "");
-                LODOP.SET_PRINT_PAGESIZE(1, 1000, 400, "CreateCustomPage");
-
-                LODOP.ADD_PRINT_HTM(9, 5, 230, 160, html);
-
-                LODOP.ADD_PRINT_TEXT(130,110,100,20,data.l_flow);
-                LODOP.SET_PRINT_STYLEA(0,"FontName","宋体");
-                LODOP.SET_PRINT_STYLEA(0,"FontSize",14);
-                LODOP.SET_PRINT_STYLEA(0,"FontColor","#000000");
-                LODOP.SET_PRINT_STYLEA(0,"Bold",1);
-
-                LODOP.SET_PRINT_STYLEA(0,"QRCodeErrorLevel","M");
-                LODOP.ADD_PRINT_BARCODE(9,240,'45mm','45mm',"QRCode",data.qrcode);
-                if (qrcode){
-                    LODOP.PREVIEW()	//打印预览
-                }else{
-                    LODOP.PRINT() // 直接打印
-                }
-
-            }
-
-            //小件码打印(10mmx5mm)
-            function print4(data,qrcode){
-                //打印二维码
-                var html = "<style>" +
-                    ".tg  {font-weight:500;}" +
-                    ".tg td{font-family:宋体, 楷体;font-size:14px;overflow:hidden;word-break:break-all;border-color:black;}" +
-                    "</style>" +
-                    "<table class=\"tg\"> <tr> <td>" + data.company_name + "</td> </tr> " +
-                    "<tr> <td >规格:" + data.product_name + "</td> </tr> " +
-                    "<tr> <td>生产批号:" + data.batch + "</td> </tr> " +
-                    "<tr> <td>日期:" + data.date + "</td> </tr></table>";
 
-                var LODOP=getLodop();
-                LODOP.PRINT_INIT("小件(10mmx5mm)");
-                LODOP.SET_LICENSES("", "152A06E8F6CBD6AC1F213ABFCB0D8604", "C94CEE276DB2187AE6B65D56B3FC2848", "");
-                LODOP.SET_PRINT_PAGESIZE(1, 1000, 500, "CreateCustomPage");
-
-                LODOP.ADD_PRINT_HTM(20, 10, 230, 160,html);
-
-                LODOP.ADD_PRINT_TEXT(160, 100, 100, 20,data.l_flow);
-                LODOP.SET_PRINT_STYLEA(0,"FontName","宋体");
-                LODOP.SET_PRINT_STYLEA(0,"FontSize",16);
-                LODOP.SET_PRINT_STYLEA(0,"FontColor","#000000");
-                LODOP.SET_PRINT_STYLEA(0,"Bold",1);
-
-                LODOP.SET_PRINT_STYLEA(0,"QRCodeErrorLevel","M");
-                LODOP.ADD_PRINT_BARCODE(25, 235, '45mm', '45mm',"QRCode",data.qrcode);
-                if (qrcode){
-                    LODOP.PREVIEW()	//打印预览
-                }else{
-                    LODOP.PRINT() // 直接打印
+            //自动打码(大件)
+            $('#print_l').click(function (e) {
+                console.log("自动打码");
+                // 检查表格是否存在
+                if ($('#table2').length === 0) {
+                    console.log("请刷新页面后重试");
+                    Toastr.error('请刷新页面后重试');
+                    return;
                 }
 
-            }
-
-            //小件码打印(10mmx6mm)
-            function print5(data,qrcode){
-                //打印二维码
-                var html = "<style>.tg  {font-weight:500;}.tg td{font-family:宋体, 楷体;font-size:14px;padding:2px 2px;overflow:hidden;word-break:break-all;border-color:black;}</style> " +
-                    "<table class=\"tg\"> <tr> <td>" + data.company_name + "</td> </tr> " +
-                    "<tr> <td >规格:" + data.product_name + "</td> </tr> " +
-                    "<tr> <td>生产批号:" + data.batch + "</td> </tr> " +
-                    "<tr> <td>日期:" + data.date + "</td> </tr></table>";
-
-                var LODOP=getLodop();
-                LODOP.PRINT_INIT("小件(10mmx6mm)");
-                LODOP.SET_LICENSES("", "152A06E8F6CBD6AC1F213ABFCB0D8604", "C94CEE276DB2187AE6B65D56B3FC2848", "");
-                LODOP.SET_PRINT_PAGESIZE(1, 1000, 600, "CreateCustomPage");
-
-                LODOP.ADD_PRINT_HTM(25, 10, 180, 160, html);
-
-                LODOP.ADD_PRINT_TEXT(180, 100, 100, 20,data.l_flow);
-                LODOP.SET_PRINT_STYLEA(0,"FontName","宋体");
-                LODOP.SET_PRINT_STYLEA(0,"FontSize",16);
-                LODOP.SET_PRINT_STYLEA(0,"FontColor","#000000");
-                LODOP.SET_PRINT_STYLEA(0,"Bold",1);
+                var rows = $('#table2').bootstrapTable('getSelections');
+                // console.log("选中的行:", rows);
 
-                LODOP.SET_PRINT_STYLEA(0,"QRCodeErrorLevel","M");
-                LODOP.ADD_PRINT_BARCODE(25, 190, '55mm', '55mm',"QRCode",data.qrcode);
-                if (qrcode){
-                    LODOP.PREVIEW()	//打印预览
-                }else{
-                    LODOP.PRINT() // 直接打印
+                // 检查是否选中了行
+                if (rows.length === 0) {
+                    Toastr.error('请先选择要打印的记录');
+                    return;
                 }
 
-            }
-
-            //跳转
-            $('#exp').click(function (e) {
-
-                $.get('qcode_bach/exp', {}, function (data) {
-                    if(data.code==1){
-                        top.window.$('[addtabs="'+data.data.id+'"]').trigger("click");
-                    }else{
-                        Toastr.error(data.msg)
-                    }
-                }, 'json');
-            })
-
-            //自动打码(大件)
-            $('#print_l').click(function (e) {
-                var rows = $('#table2').bootstrapTable('getSelections');
                 var ids = rows.map(function(item) {
-                    return item.id;
+                    // console.log("行数据:", item);
+                    // 处理MongoDB的_id对象,获取正确的ID值
+                    if (item._id && typeof item._id === 'object' && item._id.$oid) {
+                        return item._id.$oid;
+                    } else if (item._id) {
+                        return item._id;
+                    }
+                    return '';
                 });
+                // console.log("获取的ids:", ids);
 
                 var html = '<div style="margin-top: 20px">' +
                     '<label class="col-xs-5 col-sm-3" style="text-align: right;">标签类型:</label>' +
@@ -271,197 +120,40 @@ define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'LodopFuncs'], functi
                                 return false;
                             }
                             $.post('qcode_bach/print_l', {'ids':ids, 'type':type, 'numn':numn}, function (res) {
-                                if(res.code==1){
-                                    var p = 0;
-                                    var flage = 0;
-                                    for(i in res.data.rows) {
-                                        if (!flage) {
-                                            //判断预览情况
-                                            if (res.data.type == 'v010'){
-                                                print_l(res.data.rows[i], 1)
-                                            }
-                                            LODOP.On_Return = function (TaskID, Value) {
-                                                if (Value == 1) {
-                                                    p = 1;
-                                                }
-                                            }
-                                            flage++;
-                                        }else{
-                                            break;
-                                        }
-                                    }
-                                    var cint = setInterval(function () {
-                                        if (p == 1) {
-                                            clearInterval(cint);
-                                            flage = 0;
-                                            //修改打印数量
-                                            $.post('qcode_bach/set_num', {'status':1,'num':res.data.numn, 'ids':res.data.ids}, function (response) {})
-
-                                            for(i in res.data.rows) {
-                                                for(j=0;j<res.data.numn;j++){
-                                                    if (!flage){
-                                                        flage++;
-                                                    }else{
-                                                        if (res.data.type == 'v010'){
-                                                            print_l(res.data.rows[i]);//打印
-                                                        }
-                                                        flage++;
-                                                    }
-                                                }
-
-                                            }
-                                        }
-                                    },2000)
-
-                                    return false
-
-                                }else{
-                                    Toastr.error(res.msg);
+                                console.log("打印结果:", res);
+                                for(i in res.data.rows) {
+                                     print_l(res.data.rows[i], res.data.userinfo,res.data.order_number,1)
                                 }
+                                // // 处理所有选中的数据行
+                                // res.data.rows.forEach(function(row) {
+                                //     console.log("处理行数据:", row);
+                                //     // 设置为直接打印模式(参数0)
+                                //     print_l(row, res.data.userinfo, 0);
+                                // });
                             })
                         });
-
                         $(layero).find('#reset').click(function(e) {
                             e.preventDefault();
                             layer.close(layero_l);
                         });
                     }
                 });
-
             })
-            //自动打码(小件)
-            $('#print_s').click(function (e) {
-                var rows = $('#table2').bootstrapTable('getSelections');
-                var ids = rows.map(function(item) {
-                    return item.id;
-                });
-                var html = '<div style="margin-top: 20px">' +
-                    '<label class="col-xs-5 col-sm-3" style="text-align: right;">标签类型:</label>' +
-                    '<select class="selectpicker" style="height: 30px;" name="row[type]" id="type">' +
-                    '<option value="v001" datatype="">小件通用型卷烟纸(10cmX2.5cm)</option>' +
-                    '<option value="v002" datatype="">小件细支型卷烟纸(10cmX1.8cm)</option>' +
-                    '<option value="v003" datatype="">小件接装纸(10cmX4cm)</option>' +
-                    '<option value="v003" datatype="">小件内衬纸(10cmX4cm)</option>' +
-                    '<option value="v003" datatype="">小件盒包装膜(10cmX4cm)</option>' +
-                    '<option value="v003" datatype="">小件框架纸(10cmX4cm)</option>' +
-                    '<option value="v003" datatype="">小件拉线(10cmX4cm)</option>' +
-                    '<option value="v004" datatype="">小件条包装膜(10cmX5cm)</option>' +
-                    '<option value="v005" datatype="">小件盒包装纸(10cmX6cm)</option>' +
-                    '<option value="v005" datatype="">小件条包装纸(10cmX6cm)</option>' +
-                    '</select>' +
-                    '</div>' +
-                    '<div>' +
-                    '<label class="col-xs-5 col-sm-3" style="text-align: right;">打印数量:</label>' +
-                    '<input id="numn" style="width: 200px;margin-bottom: 2px;" name="row[numn]" type="text" value="1">' +
-                    '</div>' +
-                    '<div class="form-group layer-footer" style="margin-top: 10px">' +
-                    '<div style="text-align: center">' +
-                    '<button type="submit" id="btn" class="btn btn-primary btn-embossed">确认</button>' +
-                    '<button type="reset" id="reset" class="btn btn-defaults btn-embossed">取消</button>' +
-                    '</div>' +
-                    '</div>';
-
-                var layero_s = layer.open({
-                    type: 1,
-                    title: '自动打码(小件)',
-                    area: ['400px','200px'],
-                    content: html,
-                    success: function(layero) {
-                        // 在弹窗中绑定事件处理程序
-                        $(layero).find('#btn').click(function(e) {
-                            e.preventDefault();
-                            var type = $('#type').val();
-                            var numn = $('#numn').val();
-
-                            if(numn=='' || numn==0){
-                                Toastr.error('请填写打印数量');
-                                return false;
-                            }
-                            $.post('qcode_bach/print_s', {'ids':ids, 'type':type, 'numn':numn}, function (res) {
-                                if(res.code==1){
-                                    var p = 0;
-                                    var flage = 0;
-                                    for(i in res.data.rows) {
-                                        if (!flage) {
-                                            //判断预览情况
-                                            if (res.data.type == 'v001'){
-                                                print1(res.data.rows[i], 1)
-                                            }else if(res.data.type == 'v002'){
-                                                print2(res.data.rows[i], 1)
-                                            }else if(res.data.type == 'v003'){
-                                                print3(res.data.rows[i], 1)
-                                            }else if(res.data.type == 'v004'){
-                                                print4(res.data.rows[i], 1)
-                                            }else if(res.data.type == 'v005'){
-                                                print5(res.data.rows[i], 1)
-                                            }
-                                            LODOP.On_Return = function (TaskID, Value) {
-                                                if (Value == 1) {
-                                                    p = 1;
-                                                }
-                                            }
-                                            flage++;
-                                        }else{
-                                            break;
-                                        }
-                                    }
-                                    var cint = setInterval(function () {
-                                        if (p == 1) {
-                                            clearInterval(cint);
-                                            flage = 0;
-                                            //修改打印数量
-                                            $.post('qcode_bach/set_num', {'status':2,'num':res.data.numn, 'ids':res.data.ids}, function (response) {})
 
-                                            for(i in res.data.rows) {
-                                                for(j=0;j<res.data.numn;j++){
-                                                    if (!flage){
-                                                        flage++;
-                                                    }else{
-                                                        if (res.data.type == 'v001'){
-                                                            print1(res.data.rows[i])
-                                                        }else if(res.data.type == 'v002'){
-                                                            print2(res.data.rows[i])
-                                                        }else if(res.data.type == 'v003'){
-                                                            print3(res.data.rows[i])
-                                                        }else if(res.data.type == 'v004'){
-                                                            print4(res.data.rows[i])
-                                                        }else if(res.data.type == 'v005'){
-                                                            print5(res.data.rows[i])
-                                                        }
-                                                        flage++;
-                                                    }
-                                                }
-
-                                            }
-                                        }
-                                    },2000)
 
-                                    return false
+             //跳转
+            $('#exp').click(function (e) {
 
-                                }else{
-                                    Toastr.error(res.msg);
-                                }
-                            })
-                        });
-                        $(layero).find('#reset').click(function(e) {
-                            e.preventDefault();
-                            layer.close(layero_s);
-                        });
+                $.get('qcode_bach/exp', {}, function (data) {
+                    if(data.code==1){
+                        top.window.$('[addtabs="'+data.data.id+'"]').trigger("click");
+                    }else{
+                        Toastr.error(data.msg)
                     }
-                });
-
-                // Fast.api.open("qcode_bach/print_s?ids="+ids, "自动打码(小件)", {
-                //     shadeClose: true,
-                //     shade: [0.5,'#393D49'],
-                //     area: ['400px','400px'],
-                //     callback:function(value){
-                //         return false;
-                //         // 在这里可以接收弹出层中使用`Fast.api.close(data)`进行回传数据
-                //     }
-                // });
-
+                }, 'json');
             })
 
+
             //修改
             $('#edit').click(function (e) {
                 var rows = $('#table2').bootstrapTable('getSelections');
@@ -510,16 +202,16 @@ define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'LodopFuncs'], functi
                     columns: [
                         [
                             {checkbox: true},
-                            {field: 'matter_no', title: "生产批次号", operate: false, width: 100},
+                            {field: 'gdbh', title: "生产批次号", operate: false, width: 100},
                             {field: 'order_ddbh', title: "销售订单号", operate: false, width: 150},
                             {field: 'cpbm', title: "成品编码", operate: false, width: 100},
                             {field: 'matter_name', title: "成品名称", operate: false, width: 310},
                             {field: 'small_num', title: "每箱个数", operate: false, width: 100},
-                            {field: 'num', title: "总数量", operate: false, width: 80},
+                            {field: 'actual_quantity', title: "汇总", operate: false, width: 80},
                             {field: 'total_boxes', title: "每托箱数", operate: false, width: 80},
                             {field: 'tray_num', title: "每层箱数", operate: false, width: 80},
                             {field: 'box_num', title: "每托层数", operate: false, width: 80},
-                            {field: 'pallet_height', title: "每托高度", operate: false, width: 100},
+                            {field: 'layer_height', title: "每托高度", operate: false, width: 100},
                             {
                                 field: 'pallet_size',
                                 title: '托盘规格',
@@ -529,11 +221,11 @@ define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'LodopFuncs'], functi
                                     return row.pallet_length + ' * ' + row.pallet_width;
                                 }
                             },
-                            {field: 'larger_num', title: "总箱数", operate: false, width: 80},
-                            {field: 'l_flow', title: '开始流水号', operate: false, width: 120},
-                            {field: 'large_endnum', title:"结束流水号", operate: false, width: 120},
-                            {field: 'print_date', title: __('Print_date'), operate: false, width: 80},
-                            {field: 'supplier_name', title: __('Company_name'), operate: false, width: 200},
+                            {field: 'total_boxes', title: "总箱数", operate: false, width: 80},
+                            {field: 'start_pallet_no', title: '开始流水号', operate: false, width: 120},
+                            {field: 'end_pallet_no', title:"结束流水号", operate: false, width: 120},
+                            {field: 'sys_rq', title: __('Print_date'), operate: false, width: 100},
+                            // {field: 'supplier_name', title: __('Company_name'), operate: false, width: 200},
                             // {field: 'notes', title: __('Notes')},
                             // {field: 'operate', title: __('Operate'), table: table1, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                         ]
@@ -578,18 +270,18 @@ define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'LodopFuncs'], functi
                         multi_url: '',
                         table: '',
                     },
-                    onClickRow:function(row, $element, field)
-                    {
-                        Fast.api.open("qcode_bach/small?large_id="+row.id+'&l_flow='+row.l_flow, "小件列表", {
-                            shadeClose: true,
-                            shade: [0.5,'#393D49'],
-                            area: ['80%','80%'],
-                            callback:function(value){
-                                return false;
-                                // 在这里可以接收弹出层中使用`Fast.api.close(data)`进行回传数据
-                            }
-                        });
-                    },
+                    // onClickRow:function(row, $element, field)
+                    // {
+                    //     Fast.api.open("qcode_bach/small?large_id="+row.id+'&l_flow='+row.l_flow, "小件列表", {
+                    //         shadeClose: true,
+                    //         shade: [0.5,'#393D49'],
+                    //         area: ['80%','80%'],
+                    //         callback:function(value){
+                    //             return false;
+                    //             // 在这里可以接收弹出层中使用`Fast.api.close(data)`进行回传数据
+                    //         }
+                    //     });
+                    // },
                     sortOrder: 'asc',
                     toolbar: '#toolbar2',
                     pk: 'id',
@@ -606,25 +298,28 @@ define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'LodopFuncs'], functi
                     columns: [
                         [
                             {checkbox: true},
-                            {field: 'l_flow', 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) {
-                                    if(value==1){
-                                        return '<span style="color: green">已打印</span>';
-                                    }else{
-                                        return '<span>未打印</span>';
-                                    }
-                                }},
-                            {field: 'l_status', title: __('L_status'), operate: false, formatter:function (value, row, index) {
-                                    if(value==1){
-                                        return '<span style="color: green">已导出</span>';
-                                    }else{
-                                        return '<span style="color: red">未导出</span>';
-                                    }
-                                }},
+                            {field: 'pallet_no', title: __('当前托盘'), operate: false},
+                            {field: 'box_count', title: "每托箱数", operate: false},
+                            {field: 'per_box', title:"每层箱数", operate: false},
+                            {field: 'box_num', title:"每托层数", operate: false},
+                            {field: 'quantity', 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) {
+                            //         if(value==1){
+                            //             return '<span style="color: green">已打印</span>';
+                            //         }else{
+                            //             return '<span>未打印</span>';
+                            //         }
+                            //     }},
+                            // {field: 'l_status', title: __('L_status'), operate: false, formatter:function (value, row, index) {
+                            //         if(value==1){
+                            //             return '<span style="color: green">已导出</span>';
+                            //         }else{
+                            //             return '<span style="color: red">未导出</span>';
+                            //         }
+                            //     }},
                             {field: 'bach_id', title: __('bach_id'), visible:false, operate: 'LIKE'},
                             {field: 'code', title: "标签代码", operate: "LIKE"},
 
@@ -2001,6 +1696,7 @@ define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'LodopFuncs'], functi
 
             //自动打码(大件)
             $('#print_l').click(function (e) {
+                console.log(1)
                 var rows = $('#table2').bootstrapTable('getSelections');
                 var ids = rows.map(function(item) {
                     return item.id;
@@ -2345,18 +2041,18 @@ define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'LodopFuncs'], functi
                         multi_url: '',
                         table: '',
                     },
-                    onClickRow:function(row, $element, field)
-                    {
-                        Fast.api.open("qcode_bach/small?large_id="+row.id+'&l_flow='+row.l_flow, "小件列表", {
-                            shadeClose: true,
-                            shade: [0.5,'#393D49'],
-                            area: ['80%','80%'],
-                            callback:function(value){
-                                return false;
-                                // 在这里可以接收弹出层中使用`Fast.api.close(data)`进行回传数据
-                            }
-                        });
-                    },
+                    // onClickRow:function(row, $element, field)
+                    // {
+                    //     Fast.api.open("qcode_bach/small?large_id="+row.id+'&l_flow='+row.l_flow, "小件列表", {
+                    //         shadeClose: true,
+                    //         shade: [0.5,'#393D49'],
+                    //         area: ['80%','80%'],
+                    //         callback:function(value){
+                    //             return false;
+                    //             // 在这里可以接收弹出层中使用`Fast.api.close(data)`进行回传数据
+                    //         }
+                    //     });
+                    // },
                     sortOrder: 'asc',
                     toolbar: '#toolbar2',
                     pk: 'id',

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