WIN-2308041133\Administrator пре 4 дана
родитељ
комит
83a1e5d2c2

+ 159 - 81
app/admin/controller/store/StoreProduct.php

@@ -3,6 +3,7 @@
 namespace app\admin\controller\store;
 namespace app\admin\controller\store;
 
 
 use app\admin\controller\AuthController;
 use app\admin\controller\AuthController;
+use app\models\store\StoreProductLevel;
 use app\models\system\Tree;
 use app\models\system\Tree;
 use app\admin\model\store\{
 use app\admin\model\store\{
     StoreDescription,
     StoreDescription,
@@ -110,10 +111,10 @@ class StoreProduct extends AuthController
             ['type', $this->request->param('type')]
             ['type', $this->request->param('type')]
         ]);
         ]);
         $admin_id=$this->adminId;
         $admin_id=$this->adminId;
-       $mer_id = SystemAdmin::where('id',$admin_id)->value('mer_id');
-       if ($mer_id>0){
-           $where['mer_id'] = $mer_id;
-       }
+        $mer_id = SystemAdmin::where('id',$admin_id)->value('mer_id');
+        if ($mer_id>0){
+            $where['mer_id'] = $mer_id;
+        }
 
 
         return Json::successlayui(ProductModel::ProductList($where));
         return Json::successlayui(ProductModel::ProductList($where));
     }
     }
@@ -194,7 +195,7 @@ class StoreProduct extends AuthController
     }
     }
 
 
     /**
     /**
-     * 获取品详细信息
+     * 获取品详细信息
      * @param int $id
      * @param int $id
      * @throws \think\db\exception\DataNotFoundException
      * @throws \think\db\exception\DataNotFoundException
      * @throws \think\db\exception\DbException
      * @throws \think\db\exception\DbException
@@ -219,6 +220,22 @@ class StoreProduct extends AuthController
             $productInfo['cate_id'] = explode(',', $productInfo['cate_id']);
             $productInfo['cate_id'] = explode(',', $productInfo['cate_id']);
             $productInfo['description'] = htmlspecialchars_decode(StoreDescription::getDescription($id));
             $productInfo['description'] = htmlspecialchars_decode(StoreDescription::getDescription($id));
             $productInfo['slider_image'] = is_string($productInfo['slider_image']) ? json_decode($productInfo['slider_image'], true) : [];
             $productInfo['slider_image'] = is_string($productInfo['slider_image']) ? json_decode($productInfo['slider_image'], true) : [];
+
+            // 获取等级返利数据
+            $levelRebates = StoreProductLevel::where('product_id', $id)->select();
+            if ($levelRebates) {
+                $productInfo['level_rebates'] = $levelRebates->toArray();
+            } else {
+                // 默认等级数据
+                $productInfo['level_rebates'] = [
+                    ['id' => 1, 'name' => '青源客', 'rebate_ratio' => 0],
+                    ['id' => 2, 'name' => '青润使', 'rebate_ratio' => 0],
+                    ['id' => 3, 'name' => '青金团', 'rebate_ratio' => 0],
+                    ['id' => 4, 'name' => '青玉团', 'rebate_ratio' => 0],
+                    ['id' => 5, 'name' => '青谷团', 'rebate_ratio' => 0]
+                ];
+            }
+
             if ($productInfo['spec_type'] == 1) {
             if ($productInfo['spec_type'] == 1) {
                 $result = StoreProductAttrResult::getResult($id);
                 $result = StoreProductAttrResult::getResult($id);
                 foreach ($result['value'] as $k => $v) {
                 foreach ($result['value'] as $k => $v) {
@@ -302,7 +319,8 @@ class StoreProduct extends AuthController
             ['mer_use', 0],
             ['mer_use', 0],
             ['is_postage', 0],
             ['is_postage', 0],
             ['is_good', 0],
             ['is_good', 0],
-//            ['description', ''],
+            ['is_level_rebate', 0],
+            ['level_rebates', []],
             ['spec_type', 0],
             ['spec_type', 0],
             ['video_link', ''],
             ['video_link', ''],
             ['items', []],
             ['items', []],
@@ -311,13 +329,34 @@ class StoreProduct extends AuthController
             ['store_type', 1],
             ['store_type', 1],
             ['mer_id',0]
             ['mer_id',0]
         ], $this->request, false, true);
         ], $this->request, false, true);
-//        $admin_id=$this->adminId;
-//        $mer_id = SystemAdmin::where('id',$admin_id)->value('mer_id');
-//        if ($data['mer_id']>0){
-//            $data['mer_id'] = $mer_id;
-            $data['is_pick']=SystemStore::where('id',$data['mer_id'])->value('is_pick');
-//            var_dump($data);die();
-//        }
+
+        // 验证等级返利数据
+        if ($data['is_level_rebate'] == 1) {
+            if (empty($data['level_rebates']) || !is_array($data['level_rebates'])) {
+                return Json::fail('请设置等级返利数据');
+            }
+
+            // 验证返利比例是否合理
+            foreach ($data['level_rebates'] as $k => $level) {
+                if (!isset($level['rebate_ratio']) || $level['rebate_ratio'] === '') {
+                    return Json::fail('请设置等级返利比例');
+                }
+
+                if ($level['rebate_ratio'] < 0 || $level['rebate_ratio'] > 100) {
+                    return Json::fail('返利比例必须在0-100之间');
+                }
+
+                // 验证等级间返利比例是否递增
+                if ($k > 0) {
+                    if ($level['rebate_ratio'] <= $data['level_rebates'][$k-1]['rebate_ratio']) {
+                        return Json::fail('等级返利比例应随等级提高而递增');
+                    }
+                }
+            }
+        }
+
+        $data['is_pick'] = SystemStore::where('id', $data['mer_id'])->value('is_pick');
+
         foreach ($data['activity'] as $k => $v) {
         foreach ($data['activity'] as $k => $v) {
             if ($v == '秒杀') {
             if ($v == '秒杀') {
                 $data['activity'][$k] = 1;
                 $data['activity'][$k] = 1;
@@ -336,7 +375,11 @@ class StoreProduct extends AuthController
         $data['ot_price'] = min(array_column($detail, 'ot_price'));
         $data['ot_price'] = min(array_column($detail, 'ot_price'));
         $data['cost'] = min(array_column($detail, 'cost'));
         $data['cost'] = min(array_column($detail, 'cost'));
         $attr = $data['items'];
         $attr = $data['items'];
-        unset($data['items'], $data['video'], $data['attrs']);
+
+        // 保存等级返利数据
+        $levelRebates = $data['level_rebates'];
+        unset($data['items'], $data['video'], $data['attrs'], $data['level_rebates']);
+
         if (count($data['cate_id']) < 1) return Json::fail('请选择产品分类');
         if (count($data['cate_id']) < 1) return Json::fail('请选择产品分类');
         if (!in_array($data['store_type'], [1, 2])) return Json::fail('请选择正确的商品类型');
         if (!in_array($data['store_type'], [1, 2])) return Json::fail('请选择正确的商品类型');
         $cate_id = $data['cate_id'];
         $cate_id = $data['cate_id'];
@@ -348,76 +391,110 @@ class StoreProduct extends AuthController
         $data['image'] = $data['image'][0];
         $data['image'] = $data['image'][0];
         $data['slider_image'] = json_encode($data['slider_image']);
         $data['slider_image'] = json_encode($data['slider_image']);
         $data['stock'] = array_sum(array_column($detail, 'stock'));
         $data['stock'] = array_sum(array_column($detail, 'stock'));
+
         ProductModel::beginTrans();
         ProductModel::beginTrans();
-        foreach ($detail as &$item) {
-            if (($item['brokerage'] + $item['brokerage_two']) > $item['price']) {
-                return Json::fail('一二级返佣相加不能大于商品售价');
-            }
-        }
-        if ($id) {
-            unset($data['sales']);
-            ProductModel::edit($data, $id);
-            $description = $data['description'];
-            unset($data['description']);
-            StoreDescription::saveDescription($description, $id);
-            StoreProductCate::where('product_id', $id)->delete();
-            $cateData = [];
-            foreach ($cate_id as $cid) {
-                $cateData[] = ['product_id' => $id, 'cate_id' => $cid, 'add_time' => time()];
-            }
-            StoreProductCate::insertAll($cateData);
-            if ($data['spec_type'] == 0) {
-                $attr = [
-                    [
-                        'value' => '规格',
-                        'detailValue' => '',
-                        'attrHidden' => '',
-                        'detail' => ['默认']
-                    ]
-                ];
-                $detail[0]['value1'] = '规格';
-                $detail[0]['detail'] = ['规格' => '默认'];
+        try {
+            foreach ($detail as &$item) {
+                if (($item['brokerage'] + $item['brokerage_two']) > $item['price']) {
+                    throw new \Exception('一二级返佣相加不能大于商品售价');
+                }
             }
             }
 
 
-            $attr_res = StoreProductAttr::createProductAttr($attr, $detail, $id);
-            if ($attr_res) {
-                ProductModel::commitTrans();
-                return Json::success('修改成功!');
-            } else {
-                ProductModel::rollbackTrans();
-                return Json::fail(StoreProductAttr::getErrorInfo());
-            }
-        } else {
-            $data['add_time'] = time();
-            $data['code_path'] = '';
-            $res = ProductModel::create($data);
-            $description = $data['description'];
-            StoreDescription::saveDescription($description, $res['id']);
-            $cateData = [];
-            foreach ($cate_id as $cid) {
-                $cateData[] = ['product_id' => $res['id'], 'cate_id' => $cid, 'add_time' => time()];
-            }
-            StoreProductCate::insertAll($cateData);
-            if ($data['spec_type'] == 0) {
-                $attr = [
-                    [
-                        'value' => '规格',
-                        'detailValue' => '',
-                        'attrHidden' => '',
-                        'detail' => ['默认']
-                    ]
-                ];
-                $detail[0]['value1'] = '规格';
-                $detail[0]['detail'] = ['规格' => '默认'];
-            }
-            $attr_res = StoreProductAttr::createProductAttr($attr, $detail, $res['id']);
-            if ($attr_res) {
-                ProductModel::commitTrans();
-                return Json::success('添加产品成功!');
+            if ($id) {
+                unset($data['sales']);
+                ProductModel::edit($data, $id);
+                $description = $data['description'];
+                unset($data['description']);
+                StoreDescription::saveDescription($description, $id);
+                StoreProductCate::where('product_id', $id)->delete();
+                $cateData = [];
+                foreach ($cate_id as $cid) {
+                    $cateData[] = ['product_id' => $id, 'cate_id' => $cid, 'add_time' => time()];
+                }
+                StoreProductCate::insertAll($cateData);
+
+                // 更新等级返利数据
+                if ($data['is_level_rebate'] == 1) {
+                    // 删除原有数据
+                    StoreProductLevel::where('product_id', $id)->delete();
+
+                    // 插入新数据
+                    foreach ($levelRebates as $level) {
+                        StoreProductLevel::create([
+                            'product_id' => $id,
+                            'level_id' => $level['id'],
+                            'rebate_ratio' => $level['rebate_ratio'],
+                            'add_time' => time(),
+                            'update_time' => time()
+                        ]);
+                    }
+                }
+
+                if ($data['spec_type'] == 0) {
+                    $attr = [
+                        [
+                            'value' => '规格',
+                            'detailValue' => '',
+                            'attrHidden' => '',
+                            'detail' => ['默认']
+                        ]
+                    ];
+                    $detail[0]['value1'] = '规格';
+                    $detail[0]['detail'] = ['规格' => '默认'];
+                }
+
+                $attr_res = StoreProductAttr::createProductAttr($attr, $detail, $id);
+                if (!$attr_res) {
+                    throw new \Exception(StoreProductAttr::getErrorInfo());
+                }
             } else {
             } else {
-                ProductModel::rollbackTrans();
-                return Json::fail(StoreProductAttr::getErrorInfo());
+                $data['add_time'] = time();
+                $data['code_path'] = '';
+                $res = ProductModel::create($data);
+                $description = $data['description'];
+                StoreDescription::saveDescription($description, $res['id']);
+                $cateData = [];
+                foreach ($cate_id as $cid) {
+                    $cateData[] = ['product_id' => $res['id'], 'cate_id' => $cid, 'add_time' => time()];
+                }
+                StoreProductCate::insertAll($cateData);
+
+                // 保存等级返利数据
+                if ($data['is_level_rebate'] == 1) {
+                    foreach ($levelRebates as $level) {
+                        StoreProductLevel::create([
+                            'product_id' => $res['id'],
+                            'level_id' => $level['id'],
+                            'rebate_ratio' => $level['rebate_ratio'],
+                            'add_time' => time(),
+                            'update_time' => time()
+                        ]);
+                    }
+                }
+
+                if ($data['spec_type'] == 0) {
+                    $attr = [
+                        [
+                            'value' => '规格',
+                            'detailValue' => '',
+                            'attrHidden' => '',
+                            'detail' => ['默认']
+                        ]
+                    ];
+                    $detail[0]['value1'] = '规格';
+                    $detail[0]['detail'] = ['规格' => '默认'];
+                }
+                $attr_res = StoreProductAttr::createProductAttr($attr, $detail, $res['id']);
+                if (!$attr_res) {
+                    throw new \Exception(StoreProductAttr::getErrorInfo());
+                }
             }
             }
+
+            ProductModel::commitTrans();
+            return Json::success($id ? '修改成功!' : '添加产品成功!');
+        } catch (\Exception $e) {
+            ProductModel::rollbackTrans();
+            return Json::fail($e->getMessage());
         }
         }
     }
     }
 
 
@@ -480,6 +557,7 @@ class StoreProduct extends AuthController
             Form::radio('is_postage', '是否包邮', $product->getData('is_postage'))->options([['label' => '是', 'value' => 1], ['label' => '否', 'value' => 0]])->col(8),
             Form::radio('is_postage', '是否包邮', $product->getData('is_postage'))->options([['label' => '是', 'value' => 1], ['label' => '否', 'value' => 0]])->col(8),
             Form::radio('is_good', '是否优品推荐', $product->getData('is_good'))->options([['label' => '是', 'value' => 1], ['label' => '否', 'value' => 0]])->col(8),
             Form::radio('is_good', '是否优品推荐', $product->getData('is_good'))->options([['label' => '是', 'value' => 1], ['label' => '否', 'value' => 0]])->col(8),
             Form::radio('is_wholesale', '是否批发商品', $product->getData('is_wholesale'))->options([['label' => '是', 'value' => 1], ['label' => '否', 'value' => 0]])->col(8),
             Form::radio('is_wholesale', '是否批发商品', $product->getData('is_wholesale'))->options([['label' => '是', 'value' => 1], ['label' => '否', 'value' => 0]])->col(8),
+            Form::radio('is_level_rebate', '是否开启等级返利', $product->getData('is_level_rebate'))->options([['label' => '是', 'value' => 1], ['label' => '否', 'value' => 0]])->col(8),
         ];
         ];
         $form = Form::make_post_form('编辑产品', $field, Url::buildUrl('update', array('id' => $id)), 2);
         $form = Form::make_post_form('编辑产品', $field, Url::buildUrl('update', array('id' => $id)), 2);
         $this->assign(compact('form'));
         $this->assign(compact('form'));
@@ -522,6 +600,7 @@ class StoreProduct extends AuthController
             ['is_postage', 0],
             ['is_postage', 0],
             ['is_good', 0],
             ['is_good', 0],
             ['is_wholesale',0],
             ['is_wholesale',0],
+            ['is_level_rebate',0],
             ['mer_id',0]
             ['mer_id',0]
         ]);
         ]);
         if (count($data['cate_id']) < 1) return Json::fail('请选择产品分类');
         if (count($data['cate_id']) < 1) return Json::fail('请选择产品分类');
@@ -530,7 +609,6 @@ class StoreProduct extends AuthController
         if (!$data['store_name']) return Json::fail('请输入产品名称');
         if (!$data['store_name']) return Json::fail('请输入产品名称');
         if (count($data['image']) < 1) return Json::fail('请上传产品图片');
         if (count($data['image']) < 1) return Json::fail('请上传产品图片');
         if (count($data['slider_image']) < 1) return Json::fail('请上传产品轮播图');
         if (count($data['slider_image']) < 1) return Json::fail('请上传产品轮播图');
-        // if(count($data['slider_image'])>8) return Json::fail('轮播图最多5张图');
         if ($data['price'] == '' || $data['price'] < 0) return Json::fail('请输入产品售价');
         if ($data['price'] == '' || $data['price'] < 0) return Json::fail('请输入产品售价');
         if ($data['ot_price'] == '' || $data['ot_price'] < 0) return Json::fail('请输入产品市场价');
         if ($data['ot_price'] == '' || $data['ot_price'] < 0) return Json::fail('请输入产品市场价');
         if ($data['stock'] == '' || $data['stock'] < 0) return Json::fail('请输入库存');
         if ($data['stock'] == '' || $data['stock'] < 0) return Json::fail('请输入库存');
@@ -778,4 +856,4 @@ class StoreProduct extends AuthController
             return Json::fail();
             return Json::fail();
         }
         }
     }
     }
-}
+}

+ 125 - 91
app/admin/view/store/store_product/create.php

@@ -696,19 +696,6 @@
                                             </div>
                                             </div>
                                         </div>
                                         </div>
                                     </div>
                                     </div>
-<!--                                    <div class="layui-col-xs12 layui-col-sm4 layui-col-md4">-->
-<!--                                        <div class="grid-demo grid-demo-bg1">-->
-<!--                                            <div class="layui-form-item">-->
-<!--                                                <label class="layui-form-label">返利点数</label>-->
-<!--                                                <div class="layui-input-block">-->
-<!--                                                    <input type="number" name="rebate_ratio" lay-verify="title"-->
-<!--                                                           autocomplete="off"-->
-<!--                                                           placeholder="请输入返利点数" class="layui-input"-->
-<!--                                                           v-model="formData.rebate_ratio">-->
-<!--                                                </div>-->
-<!--                                            </div>-->
-<!--                                        </div>-->
-<!--                                    </div>-->
                                     <div class="layui-col-xs12 layui-col-sm4 layui-col-md4">
                                     <div class="layui-col-xs12 layui-col-sm4 layui-col-md4">
                                         <div class="grid-demo grid-demo-bg1">
                                         <div class="grid-demo grid-demo-bg1">
                                             <div class="layui-form-item">
                                             <div class="layui-form-item">
@@ -734,9 +721,9 @@
                                             </div>
                                             </div>
                                         </div>
                                         </div>
                                     </div>
                                     </div>
-                                    <div class="layui-col-xs12 layui-col-sm12 layui-col-md12">
-                                        <div class="grid-demo grid-demo-bg1">
-                                            <div class="layui-form-item">
+<!--                                    <div class="layui-col-xs12 layui-col-sm12 layui-col-md12">-->
+<!--                                        <div class="grid-demo grid-demo-bg1">-->
+<!--                                            <div class="layui-form-item">-->
 <!--                                                <label class="layui-form-label">佣金设置</label>-->
 <!--                                                <label class="layui-form-label">佣金设置</label>-->
 <!--                                                <div class="layui-input-block">-->
 <!--                                                <div class="layui-input-block">-->
 <!--                                                    <input type="radio" name="is_sub" lay-filter="is_sub" value="1"-->
 <!--                                                    <input type="radio" name="is_sub" lay-filter="is_sub" value="1"-->
@@ -746,9 +733,9 @@
 <!--                                                           title="默认设置"-->
 <!--                                                           title="默认设置"-->
 <!--                                                           :checked="formData.is_sub == 0 ? true : false">-->
 <!--                                                           :checked="formData.is_sub == 0 ? true : false">-->
 <!--                                                </div>-->
 <!--                                                </div>-->
-                                            </div>
-                                        </div>
-                                    </div>
+<!--                                            </div>-->
+<!--                                        </div>-->
+<!--                                    </div>-->
                                     <div class="layui-col-xs12 layui-col-sm12 layui-col-md12"
                                     <div class="layui-col-xs12 layui-col-sm12 layui-col-md12"
                                          v-if="formData.is_sub == 1 && formData.spec_type == 1">
                                          v-if="formData.is_sub == 1 && formData.spec_type == 1">
                                         <div class="grid-demo grid-demo-bg1">
                                         <div class="grid-demo grid-demo-bg1">
@@ -869,19 +856,6 @@
                                     </div>
                                     </div>
                                     <!--多属性结束-->
                                     <!--多属性结束-->
 
 
-                                    <!--                                    <div class="layui-col-xs12 layui-col-sm4 layui-col-md4">-->
-                                    <!--                                        <div class="grid-demo grid-demo-bg1">-->
-                                    <!--                                            <div class="layui-form-item">-->
-                                    <!--                                                <label class="layui-form-label">商品状态</label>-->
-                                    <!--                                                <div class="layui-input-block">-->
-                                    <!--                                                    <input type="radio" name="is_show" lay-filter="is_show" value="1" title="上架"-->
-                                    <!--                                                           :checked="formData.is_show == 1 ? true : false">-->
-                                    <!--                                                    <input type="radio" name="is_show" lay-filter="is_show" value="0" title="下架"-->
-                                    <!--                                                           :checked="formData.is_show == 0 ? true : false">-->
-                                    <!--                                                </div>-->
-                                    <!--                                            </div>-->
-                                    <!--                                        </div>-->
-                                    <!--                                    </div>-->
                                     <div class="layui-col-xs12 layui-col-sm4 layui-col-md4">
                                     <div class="layui-col-xs12 layui-col-sm4 layui-col-md4">
                                         <div class="grid-demo grid-demo-bg1">
                                         <div class="grid-demo grid-demo-bg1">
                                             <div class="layui-form-item">
                                             <div class="layui-form-item">
@@ -972,28 +946,52 @@
                                             </div>
                                             </div>
                                         </div>
                                         </div>
                                     </div>
                                     </div>
-<!--                                    <div class="layui-row layui-col-space15">-->
-<!--                                        <div class="layui-col-xs12 layui-col-sm12 layui-col-md12">-->
-<!--                                            <div class="grid-demo grid-demo-bg1">-->
-<!--                                                <div class="layui-form-item">-->
-<!--                                                    <label class="layui-form-label">活动优先级</label>-->
-<!--                                                    <div class="layui-input-block">-->
-<!--                                                        <span class="layui-btn layui-btn-sm layui-btn-normal"-->
-<!--                                                              :style="'background-color:'+activity[item]"-->
-<!--                                                              v-for="(item,index) in formData.activity" :key="index"-->
-<!--                                                              draggable="true"-->
-<!--                                                              @dragstart="handleDragStart($event, item)"-->
-<!--                                                              @dragover.prevent="handleDragOver($event, item)"-->
-<!--                                                              @dragenter="handleDragEnter($event, item)"-->
-<!--                                                              @dragend="handleDragEnd($event, item)">-->
-<!--                                                        {{item}}-->
-<!--                                                    </span>-->
-<!--                                                        <span class="info">可拖动按钮调整活动的优先展示顺序</span>-->
-<!--                                                    </div>-->
-<!--                                                </div>-->
-<!--                                            </div>-->
-<!--                                        </div>-->
-<!--                                    </div>-->
+                                    <div class="layui-col-xs12 layui-col-sm12 layui-col-md12">
+                                        <div class="grid-demo grid-demo-bg1">
+                                            <div class="layui-form-item">
+                                                <label class="layui-form-label">等级返利设置</label>
+                                                <div class="layui-input-block">
+                                                    <input type="radio" name="is_level_rebate" lay-filter="is_level_rebate" value="1"
+                                                           title="开启"
+                                                           :checked="formData.is_level_rebate == 1 ? true : false">
+                                                    <input type="radio" name="is_level_rebate" lay-filter="is_level_rebate" value="0"
+                                                           title="关闭"
+                                                           :checked="formData.is_level_rebate == 0 ? true : false">
+                                                </div>
+                                            </div>
+                                        </div>
+                                    </div>
+                                    <div class="layui-col-xs12 layui-col-sm12 layui-col-md12" v-if="formData.is_level_rebate == 1">
+                                        <div class="grid-demo grid-demo-bg1">
+                                            <div class="layui-form-item">
+                                                <label class="layui-form-label">等级返利比例</label>
+                                                <div class="layui-input-block">
+                                                    <table class="layui-table">
+                                                        <thead>
+                                                        <tr>
+                                                            <th>等级名称</th>
+                                                            <th>返利比例(%)</th>
+                                                        </tr>
+                                                        </thead>
+                                                        <tbody>
+                                                        <tr v-for="(level, index) in formData.level_rebates" :key="level.id">
+                                                            <td>{{level.name}}</td>
+                                                            <td>
+                                                                <input type="number" v-model="level.rebate_ratio"
+                                                                       class="layui-input"
+                                                                       min="0"
+                                                                       max="100"
+                                                                       step="0.01"
+                                                                       @change="checkRebateRatio(level)">
+                                                            </td>
+                                                        </tr>
+                                                        </tbody>
+                                                    </table>
+                                                    <div class="layui-form-mid layui-word-aux red" v-if="rebateError">{{rebateError}}</div>
+                                                </div>
+                                            </div>
+                                        </div>
+                                    </div>
                                 </div>
                                 </div>
                             </div>
                             </div>
                         </div>
                         </div>
@@ -1091,16 +1089,18 @@
                 is_good: 0,
                 is_good: 0,
                 store_type: 1,
                 store_type: 1,
                 is_sub: 0,
                 is_sub: 0,
-                items: [
-                    // {
-                    //     value: '',
-                    //     detailValue:'',
-                    //     attrHidden:false,
-                    //     detail:[]
-                    // }
+                is_level_rebate: 0,
+                level_rebates: [
+                    {id: 1, name: '青源客', rebate_ratio: 0},
+                    {id: 2, name: '青润使', rebate_ratio: 0},
+                    {id: 3, name: '青金团', rebate_ratio: 0},
+                    {id: 4, name: '青玉团', rebate_ratio: 0},
+                    {id: 5, name: '青谷团', rebate_ratio: 0}
                 ],
                 ],
+                items: [],
                 activity: ['秒杀', '砍价', '拼团'],
                 activity: ['秒杀', '砍价', '拼团'],
             },
             },
+            rebateError: '',
             videoLink: '',
             videoLink: '',
             //批量添加属性
             //批量添加属性
             batchAttr: {
             batchAttr: {
@@ -1128,7 +1128,7 @@
             activity: {'秒杀': '#1E9FFF', '砍价': '#189688', '拼团': '#FEB900'},
             activity: {'秒杀': '#1E9FFF', '砍价': '#189688', '拼团': '#FEB900'},
             attr: [],//临时属性
             attr: [],//临时属性
             newRule: false,//是否添加新规则
             newRule: false,//是否添加新规则
-            radioRule: ['store_type', 'is_sub', 'is_show', 'is_hot', 'is_benefit', 'is_new', 'is_good', 'is_best','is_wholesale', 'spec_type'],//radio 当选规则
+            radioRule: ['store_type', 'is_sub', 'is_show', 'is_hot', 'is_benefit', 'is_new', 'is_good', 'is_best','is_wholesale', 'spec_type', 'is_level_rebate'],//radio 当选规则
             rule: { //多图选择规则
             rule: { //多图选择规则
                 slider_image: {
                 slider_image: {
                     maxLength: 5
                     maxLength: 5
@@ -1157,14 +1157,12 @@
                     this.render();
                     this.render();
                 }
                 }
             },
             },
-            // 'formData.image':function (n) {
-            //     if(!this.batchAttr.pic){
-            //         this.batchAttr.pic = n;
-            //     }
-            //     if(!this.formData.attr.pic){
-            //         this.formData.attr.pic = n;
-            //     }
-            // }
+            'formData.is_level_rebate': function (n) {
+                if (n == 1) {
+                    // 开启等级返利时,清空返利错误提示
+                    this.rebateError = '';
+                }
+            }
         },
         },
         methods: {
         methods: {
             back: function () {
             back: function () {
@@ -1202,6 +1200,41 @@
                     layui.layer.msg(msg, success);
                     layui.layer.msg(msg, success);
                 });
                 });
             },
             },
+            /**
+             * 检查返利比例是否合理
+             */
+            checkRebateRatio: function (level) {
+                this.rebateError = '';
+                // 检查是否为数字
+                if (isNaN(level.rebate_ratio) || level.rebate_ratio === '') {
+                    this.rebateError = level.name + '的返利比例必须是数字';
+                    return false;
+                }
+
+                // 检查是否在合理范围内
+                if (level.rebate_ratio < 0 || level.rebate_ratio > 100) {
+                    this.rebateError = level.name + '的返利比例必须在0-100之间';
+                    return false;
+                }
+
+                // 检查是否超过成本价
+                if (this.formData.spec_type == 0 && this.formData.attr.cost > 0) {
+                    if (level.rebate_ratio > (this.formData.attr.price - this.formData.attr.cost) / this.formData.attr.price * 100) {
+                        this.rebateError = level.name + '的返利比例过高,可能影响平台利润';
+                        return false;
+                    }
+                }
+
+                // 检查等级间返利比例是否递增
+                for (let i = 0; i < this.formData.level_rebates.length - 1; i++) {
+                    if (this.formData.level_rebates[i].rebate_ratio > this.formData.level_rebates[i + 1].rebate_ratio) {
+                        this.rebateError = '等级返利比例应随等级提高而递增';
+                        return false;
+                    }
+                }
+
+                return true;
+            },
             addBrokerage: function () {
             addBrokerage: function () {
                 if (this.brokerage.brokerage > 0 && this.brokerage.brokerage_two > 0) {
                 if (this.brokerage.brokerage > 0 && this.brokerage.brokerage_two > 0) {
                     var that = this;
                     var that = this;
@@ -1280,6 +1313,18 @@
                     var productInfo = res.data.productInfo || {};
                     var productInfo = res.data.productInfo || {};
                     if (productInfo.id && that.id) {
                     if (productInfo.id && that.id) {
                         that.$set(that, 'formData', productInfo);
                         that.$set(that, 'formData', productInfo);
+                        // 初始化等级返利数据
+                        if (productInfo.level_rebates) {
+                            that.formData.level_rebates = productInfo.level_rebates;
+                        } else {
+                            that.formData.level_rebates = [
+                                {id: 1, name: '青源客', rebate_ratio: 0},
+                                {id: 2, name: '青润使', rebate_ratio: 0},
+                                {id: 3, name: '青金团', rebate_ratio: 0},
+                                {id: 4, name: '青玉团', rebate_ratio: 0},
+                                {id: 5, name: '青谷团', rebate_ratio: 0}
+                            ];
+                        }
                         that.generate();
                         that.generate();
                     }
                     }
                     that.getRuleList();
                     that.getRuleList();
@@ -1645,6 +1690,16 @@
                 if (!that.formData.slider_image.length) {
                 if (!that.formData.slider_image.length) {
                     return that.showMsg('请填选择商品轮播图');
                     return that.showMsg('请填选择商品轮播图');
                 }
                 }
+
+                // 检查等级返利设置
+                if (that.formData.is_level_rebate == 1) {
+                    for (let i = 0; i < that.formData.level_rebates.length; i++) {
+                        if (!that.checkRebateRatio(that.formData.level_rebates[i])) {
+                            return;
+                        }
+                    }
+                }
+
                 if (that.formData.spec_type == 0) {
                 if (that.formData.spec_type == 0) {
                     if (!that.formData.attr.pic) {
                     if (!that.formData.attr.pic) {
                         return that.showMsg('请选择单规则图片');
                         return that.showMsg('请选择单规则图片');
@@ -1732,27 +1787,6 @@
                     });
                     });
                 })
                 })
             },
             },
-            // 移动
-            handleDragStart(e, item) {
-                this.dragging = item;
-            },
-            handleDragEnd(e, item) {
-                this.dragging = null
-            },
-            handleDragOver(e) {
-                e.dataTransfer.dropEffect = 'move'
-            },
-            handleDragEnter(e, item) {
-                e.dataTransfer.effectAllowed = 'move'
-                if (item === this.dragging) {
-                    return
-                }
-                var newItems = [...this.formData.activity];
-                var src = newItems.indexOf(this.dragging);
-                var dst = newItems.indexOf(item);
-                newItems.splice(dst, 0, ...newItems.splice(src, 1))
-                this.formData.activity = newItems;
-            },
             getRuleList: function (type) {
             getRuleList: function (type) {
                 var that = this;
                 var that = this;
                 that.requestGet(that.U({c: 'store.StoreProduct', a: 'get_rule'})).then(function (res) {
                 that.requestGet(that.U({c: 'store.StoreProduct', a: 'get_rule'})).then(function (res) {

+ 229 - 43
app/models/store/StoreOrder.php

@@ -152,12 +152,12 @@ class StoreOrder extends BaseModel
             }
             }
             if ($storeFreePostage <= $totalPrice) $storePostage = 0;//如果总价大于等于满额包邮 邮费等于0
             if ($storeFreePostage <= $totalPrice) $storePostage = 0;//如果总价大于等于满额包邮 邮费等于0
 
 
-            if ($temp['collect_on_delivery']==1){
+            if ($temp['collect_on_delivery'] == 1) {
                 $storePostage = 0;
                 $storePostage = 0;
                 $collect_on_delivery = 1;
                 $collect_on_delivery = 1;
             }
             }
         }
         }
-        return compact('storePostage', 'storeFreePostage', 'totalPrice', 'costPrice', 'vipPrice', 'totalIntegral','collect_on_delivery');
+        return compact('storePostage', 'storeFreePostage', 'totalPrice', 'costPrice', 'vipPrice', 'totalIntegral', 'collect_on_delivery');
     }
     }
 
 
 
 
@@ -302,7 +302,7 @@ class StoreOrder extends BaseModel
             $payPrice = (float)$priceGroup['totalPrice'];
             $payPrice = (float)$priceGroup['totalPrice'];
             $payIntegral = (float)$priceGroup['totalIntegral'];
             $payIntegral = (float)$priceGroup['totalIntegral'];
             $addr = UserAddress::where('uid', $uid)->where('id', $addressId)->find();
             $addr = UserAddress::where('uid', $uid)->where('id', $addressId)->find();
-            $collect_on_delivery=0;
+            $collect_on_delivery = 0;
             if ($payType == 'offline' && sys_config('offline_postage') == 1) {
             if ($payType == 'offline' && sys_config('offline_postage') == 1) {
                 $payPostage = 0;
                 $payPostage = 0;
             } else {
             } else {
@@ -557,20 +557,20 @@ class StoreOrder extends BaseModel
             $total_num = 0;
             $total_num = 0;
             $total_price = 0;
             $total_price = 0;
             $deduction_price = 0;
             $deduction_price = 0;
-            @file_put_contents('quanju4.txt',  json_encode($v)."-测试1\r\n", 8);
+            @file_put_contents('quanju4.txt', json_encode($v) . "-测试1\r\n", 8);
 
 
             $cartInfo = StoreCart::where('id', 'in', $v['ids'])->select();
             $cartInfo = StoreCart::where('id', 'in', $v['ids'])->select();
-            @file_put_contents('quanju4.txt',  json_encode($cartInfo)."-测试5\r\n", 8);
+            @file_put_contents('quanju4.txt', json_encode($cartInfo) . "-测试5\r\n", 8);
 
 
             foreach ($cartInfo as $cart) {
             foreach ($cartInfo as $cart) {
-                @file_put_contents('quanju4.txt',  json_encode($cart['product_id'])."-测试3\r\n", 8);
+                @file_put_contents('quanju4.txt', json_encode($cart['product_id']) . "-测试3\r\n", 8);
 
 
                 $price = StoreProduct::where('id', $cart['product_id'])->value('price');
                 $price = StoreProduct::where('id', $cart['product_id'])->value('price');
                 $product_price = bcmul($price, $cart['cart_num'], 2);
                 $product_price = bcmul($price, $cart['cart_num'], 2);
                 $total_price = bcadd($total_price, $product_price, 2); //商品总价
                 $total_price = bcadd($total_price, $product_price, 2); //商品总价
                 $total_num = bcadd($total_num, $cart['cart_num'], 2);
                 $total_num = bcadd($total_num, $cart['cart_num'], 2);
             }
             }
-            @file_put_contents('quanju4.txt',  "-这里吗\r\n", 8);
+            @file_put_contents('quanju4.txt', "-这里吗\r\n", 8);
 
 
             if ($user_info['level'] > 0) { //会员折扣
             if ($user_info['level'] > 0) { //会员折扣
                 $discount = SystemUserLevel::where('id', $user_info['level'])->value('discount');
                 $discount = SystemUserLevel::where('id', $user_info['level'])->value('discount');
@@ -578,7 +578,7 @@ class StoreOrder extends BaseModel
                 $total_price = bcmul($total_price, bcsub(1, $discount, 2), 2);
                 $total_price = bcmul($total_price, bcsub(1, $discount, 2), 2);
                 $deduction_price = bcsub($moto_price, $total_price, 2); //抵扣金额
                 $deduction_price = bcsub($moto_price, $total_price, 2); //抵扣金额
             }
             }
-            @file_put_contents('quanju4.txt',  "-测试4\r\n", 8);
+            @file_put_contents('quanju4.txt', "-测试4\r\n", 8);
 
 
             $orderInfo = [
             $orderInfo = [
                 'mer_id' => $v['mer_id'],
                 'mer_id' => $v['mer_id'],
@@ -913,15 +913,196 @@ class StoreOrder extends BaseModel
         UserBill::expend('购买商品', $order['uid'], 'now_money', 'pay_money', $order['pay_price'], $order['id'], $now_money, '支付' . floatval($order['pay_price']) . '元购买商品');
         UserBill::expend('购买商品', $order['uid'], 'now_money', 'pay_money', $order['pay_price'], $order['id'], $now_money, '支付' . floatval($order['pay_price']) . '元购买商品');
         //支付成功后
         //支付成功后
         event('OrderPaySuccess', [$order, $formId]);
         event('OrderPaySuccess', [$order, $formId]);
-        self::userLevelReward($order, $order['uid'], 1);  //激励奖 会员返现
+//        self::userLevelReward($order, $order['uid'], 1);  //激励奖 会员返现
         if ($order['is_wholesale'] == 1) {  //批发订单
         if ($order['is_wholesale'] == 1) {  //批发订单
-            self::wholesale($order);  //批发订单返利
-            self::umbrella($order);  //伞下返利
+//            self::wholesale($order);  //批发订单返利
+//            self::umbrella($order);  //伞下返利
         }
         }
         $res = $res1 && $resPink && UserSpread::setSpreadSure($order['uid']) && User::backOrderBrokerage($order);
         $res = $res1 && $resPink && UserSpread::setSpreadSure($order['uid']) && User::backOrderBrokerage($order);
         return false !== $res;
         return false !== $res;
     }
     }
 
 
+    public static function userLevelRewards($order, $uid)
+    {
+
+    }
+    /**
+     * 无限级分销返利方法
+     * @param array $order 订单信息
+     * @param int $uid 购买者用户ID
+     * @param float $orderAmount 订单金额
+     * @return bool 处理结果
+     */
+//    public static function infiniteRebate($order, $uid, $orderAmount)
+//    {
+//        try {
+//            // 获取购买者信息
+//            $buyerInfo = User::get($uid);
+//            if (empty($buyerInfo)) {
+//
+//                return false;
+//            }
+//
+//            $buyerLevel = $buyerInfo['level'];
+//
+//            // 开始递归查找上级并处理返利
+//            return self::processRebate($order, $buyerInfo['spread_uid'], $buyerLevel, $orderAmount, 0, false);
+//        } catch (\Exception $e) {
+//            return false;
+//        }
+//    }
+
+    /**
+     * 递归处理 商品返利
+     * @param array $order 订单信息
+     * @param int $uid 当前处理的用户ID
+     * @param int $parentLevel 上级等级
+     * @param int $parentBrokerage 上级等级获得金额
+     * @return bool 处理结果
+     */
+    private static function processRebate($order, $uid, $parentLevel = 0, $parentBrokerage = 0)
+    {
+        $brokerage = 0;  //奖励金额
+        $user = User::get($uid);
+        $blance = $user['brokerage_price'];
+        $level_info = SystemUserLevel::where('id', $user['level'])->where('is_del', 0)->find();
+        if (!empty($level_info)) {
+            $level_info = $level_info->toArray();
+        }
+        if ($parentLevel > 0) {
+//            $parent_level_info= SystemUserLevel::where('grade')->where('is_del',0)->find();
+//            if (!empty($parent_level_info)){
+//                $parent_level_info = $parent_level_info->toArray();
+//                if ()
+//            }
+            if ($parentLevel > $level_info['grade']) {  //如果上上级等级小于上级,就直接跳过
+                if ($user['spread_uid'] > 0) {
+                    self::processRebate($order, $user['spread_uid'], $parentLevel, $parentBrokerage);
+                }
+            } elseif ($parentLevel == $level_info['grade']) {  //如果上上级等级等于上级,就获取上级佣金的10%
+
+                $userPeerLevel = sys_config('user_peer_level', 10);
+                if ($userPeerLevel > 0) {
+                    $userPeerLevel = bcmul($userPeerLevel, 0.01, 2);
+                    $brokerage = bcmul($parentBrokerage, $userPeerLevel, 2);
+                }
+            } elseif ($parentLevel < $parentLevel['grade']) {  //如果上上级等级大于上级,就获取自己等级返利的佣金
+//                StoreProductLevel::where('product_id',$)
+                $shopping_cart = $order['cart_id'];
+//            先不考虑什么商品返现比例了
+                foreach ($shopping_cart as $cart) {
+//                @file_put_contents('quanju4.txt', $cart . "-购物车id2\r\n", 8);
+                    $product_radio = 0;
+                    $product_info = StoreCart::where('id', $cart)->find()->toArray();
+
+                    $product = StoreProductLevel::where('id', $product_info['product_id'])->where('level_id', $user['level'])->find();  //商品返现比例
+                    if (!empty($product)) {
+                        $product = $product->toArray();
+                        $product_radio = $product['rebate_ratio'];
+                    }
+
+
+                    if ($product_radio > 0) {
+//                    if ($user_radio>0){
+                        $product_price = StoreProduct::where('id', $product_info['product_id'])->value('price');
+                        $rebate = bcmul($product_price, bcdiv($product_radio, 100, 2), 2);  //商品返现金额
+                        $brokerage = bcadd($brokerage, $rebate, 2);
+//                    }
+                    }
+
+                }
+            }
+        }
+
+        // 如果返利金额大于0,添加佣金记录
+        if ($brokerage > 0) {
+            $newBalance = bcadd($user['brokerage_price'], $brokerage, 2);
+//            if ($parentLevel ==0 && $parentBrokerage == 0){
+//                UserBill::income('商品返利', $uid, 'brokerage_price', 'order_money', $brokerage, $order['id'], $newBalance, '购买商品的商品返利佣金');
+//
+//            }else{
+                UserBill::income('下级商品返利', $uid, 'brokerage_price', 'order_money', $brokerage, $order['id'], $newBalance, '下级购买商品的商品返利佣金');
+
+//            }
+            User::where('uid', $uid)->update(['brokerage_price' => $newBalance]);
+
+
+            if ($user['spread_uid'] > 0) {
+                self::processRebate($order, $user['spread_uid'], $level_info['grade']);
+            } else {
+                return true;
+            }
+        }
+        return true;
+    }
+    /**
+     * 获取商品积分返利
+     * @return float 返利比例
+     */
+    private static function getProductIntegral($order,$uid)
+    {
+        try {
+            $shopping_cart = $order['cart_id'];
+            $integral = 0;
+            $user = User::get($uid);
+//            先不考虑什么商品返现比例了
+            foreach ($shopping_cart as $cart) {
+//                @file_put_contents('quanju4.txt', $cart . "-购物车id2\r\n", 8);
+                $product_radio = 0;
+                $product_info = StoreCart::where('id', $cart)->find()->toArray();
+
+                $product = StoreProduct::where('id', $product_info['product_id'])->find();  //商品信息
+                if (!empty($product)) {
+                    $product = $product->toArray();
+                    $product_radio = $product['rebate_ratio'];
+                }
+
+
+                if ($product_radio > 0) {
+//                    if ($user_radio>0){
+//                    $product_price = StoreProduct::where('id', $product_info['product_id'])->value('price');
+                    $rebate = bcmul($product['price'], bcdiv($product_radio, 100, 2), 2);  //商品返现金额
+                    $integral = bcadd($integral, $rebate, 2);
+//                    }
+                }
+
+            }
+            $newBalance = bcadd($user['integral'],$integral,2);
+            UserBill::income('商品返利', $uid, 'integral', 'order_integral', $integral, $order['id'], $newBalance, '购买商品的商品返利积分');
+
+//            }
+            User::where('uid', $uid)->update(['integral' => $newBalance]);
+
+            return true;
+        } catch (\Exception $e) {
+            @file_put_contents('quanju.txt', json_encode(['line' => $e->getLine(), 'message' => $e->getMessage(), 'file' => $e->getFile()]) . "-报错内容\r\n", 8);
+        }
+    }
+    /**
+     * 获取商品等级返利比例
+     * @param int $productId 商品ID
+     * @param int $levelId 等级ID
+     * @return float 返利比例
+     */
+    private static function getProductLevelRebate($productId, $levelId)
+    {
+        try {
+            // 先从商品等级返利表中获取
+            $rebateRatio = StoreProductLevel::where('product_id', $productId)
+                ->where('level_id', $levelId)
+                ->value('rebate_ratio');
+
+            // 如果商品等级没有设置返利比例,使用等级表中的默认比例
+            if (empty($rebateRatio)) {
+                $rebateRatio = SystemUserLevel::where('id', $levelId)->value('rebate_ratio');
+            }
+
+            return floatval($rebateRatio);
+        } catch (\Exception $e) {
+            return 0;
+        }
+    }
+
 //    激励奖 会员返现
 //    激励奖 会员返现
     public static function userLevelReward($order, $uid, $type)
     public static function userLevelReward($order, $uid, $type)
     {
     {
@@ -934,7 +1115,7 @@ class StoreOrder extends BaseModel
                 @file_put_contents('quanju4.txt', json_encode($user_radio) . "-会员等级返利比例\r\n", 8);
                 @file_put_contents('quanju4.txt', json_encode($user_radio) . "-会员等级返利比例\r\n", 8);
 
 
                 $rebate = bcmul($order['pay_price'], bcdiv($user_radio, 100, 2), 2);  //用户返现金额
                 $rebate = bcmul($order['pay_price'], bcdiv($user_radio, 100, 2), 2);  //用户返现金额
-                if ($rebate > 0){
+                if ($rebate > 0) {
                     $blance = bcadd($userInfo['brokerage_price'], $rebate, 2);  //用户佣金
                     $blance = bcadd($userInfo['brokerage_price'], $rebate, 2);  //用户佣金
                     @file_put_contents('quanju4.txt', json_encode(['line' => $rebate, 'message' => $order['id'], 'file' => $blance]) . "-会员等级激励奖报错内容2\r\n", 8);
                     @file_put_contents('quanju4.txt', json_encode(['line' => $rebate, 'message' => $order['id'], 'file' => $blance]) . "-会员等级激励奖报错内容2\r\n", 8);
 
 
@@ -947,23 +1128,23 @@ class StoreOrder extends BaseModel
                         UserBill::income('下级会员返利', $uid, 'brokerage_price', 'level_money', $rebate, $order['id'], $blance, '下级购买商品的会员返利佣金');
                         UserBill::income('下级会员返利', $uid, 'brokerage_price', 'level_money', $rebate, $order['id'], $blance, '下级购买商品的会员返利佣金');
                         return true;
                         return true;
                     }
                     }
-                    User::where('uid',$uid)->update(['brokerage_price'=>$blance]);
+                    User::where('uid', $uid)->update(['brokerage_price' => $blance]);
 
 
                 }
                 }
             }
             }
-                $rebate=0;
-                $userInfo = User::get($uid);
-                @file_put_contents('quanju4.txt',json_encode($order['cart_id']) . "-购物车id1\r\n", 8);
+            $rebate = 0;
+            $userInfo = User::get($uid);
+            @file_put_contents('quanju4.txt', json_encode($order['cart_id']) . "-购物车id1\r\n", 8);
 //            $shopping_cart = json_decode($order['cart_id'], true);
 //            $shopping_cart = json_decode($order['cart_id'], true);
             $shopping_cart = $order['cart_id'];
             $shopping_cart = $order['cart_id'];
 //            先不考虑什么商品返现比例了
 //            先不考虑什么商品返现比例了
             foreach ($shopping_cart as $cart) {
             foreach ($shopping_cart as $cart) {
-                @file_put_contents('quanju4.txt',$cart . "-购物车id2\r\n", 8);
-                $product_radio=0;
+                @file_put_contents('quanju4.txt', $cart . "-购物车id2\r\n", 8);
+                $product_radio = 0;
                 $product_info = StoreCart::where('id', $cart)->find()->toArray();
                 $product_info = StoreCart::where('id', $cart)->find()->toArray();
                 @file_put_contents('quanju4.txt', json_encode($product_info) . "-购物车详情\r\n", 8);
                 @file_put_contents('quanju4.txt', json_encode($product_info) . "-购物车详情\r\n", 8);
                 $product = StoreProduct::where('id', $product_info['product_id'])->find();  //商品返现比例
                 $product = StoreProduct::where('id', $product_info['product_id'])->find();  //商品返现比例
-                if (!empty($product)){
+                if (!empty($product)) {
                     $product = $product->toArray();
                     $product = $product->toArray();
                     $product_radio = $product['rebate_ratio'];
                     $product_radio = $product['rebate_ratio'];
                 }
                 }
@@ -971,23 +1152,23 @@ class StoreOrder extends BaseModel
                 @file_put_contents('quanju4.txt', $product_radio . "-会员等级激励奖报错内容4\r\n", 8);
                 @file_put_contents('quanju4.txt', $product_radio . "-会员等级激励奖报错内容4\r\n", 8);
 
 
 
 
-                if ($product_radio>0){
+                if ($product_radio > 0) {
 //                    if ($user_radio>0){
 //                    if ($user_radio>0){
                     $rebate = bcmul($order['pay_price'], bcdiv($product_radio, 100, 2), 2);  //用户返现金额
                     $rebate = bcmul($order['pay_price'], bcdiv($product_radio, 100, 2), 2);  //用户返现金额
 
 
-                        $blance = bcadd($userInfo['brokerage_price'], $rebate, 2);  //用户佣金
-                        @file_put_contents('quanju4.txt', json_encode(['line' => $rebate, 'message' => $order['id'], 'file' => $blance]) . "-会员等级激励奖报错内容2\r\n", 8);
+                    $blance = bcadd($userInfo['brokerage_price'], $rebate, 2);  //用户佣金
+                    @file_put_contents('quanju4.txt', json_encode(['line' => $rebate, 'message' => $order['id'], 'file' => $blance]) . "-会员等级激励奖报错内容2\r\n", 8);
 
 
-                        if ($type == 1) {
-                            UserBill::income('商品返利', $uid, 'brokerage_price', 'order_money', $rebate, $order['id'], $blance, '商品返利佣金');
+                    if ($type == 1) {
+                        UserBill::income('商品返利', $uid, 'brokerage_price', 'order_money', $rebate, $order['id'], $blance, '商品返利佣金');
 //                            if ($userInfo['spread_uid'] > 0) {
 //                            if ($userInfo['spread_uid'] > 0) {
 //                                self::userLevelReward($order, $userInfo['spread_uid'], 2);
 //                                self::userLevelReward($order, $userInfo['spread_uid'], 2);
 //                            }
 //                            }
-                        } elseif ($type == 2) { //下级推荐返利
-                            UserBill::income('下级商品返利', $uid, 'brokerage_price', 'order_money', $rebate, $order['id'], $blance, '下级购买商品的商品返利佣金');
-                            return true;
-                        }
-                        User::where('uid',$uid)->update(['brokerage_price'=>$blance]);
+                    } elseif ($type == 2) { //下级推荐返利
+                        UserBill::income('下级商品返利', $uid, 'brokerage_price', 'order_money', $rebate, $order['id'], $blance, '下级购买商品的商品返利佣金');
+                        return true;
+                    }
+                    User::where('uid', $uid)->update(['brokerage_price' => $blance]);
 //                    }
 //                    }
                 }
                 }
                 if ($userInfo['spread_uid'] > 0) {
                 if ($userInfo['spread_uid'] > 0) {
@@ -995,7 +1176,7 @@ class StoreOrder extends BaseModel
                 }
                 }
             }
             }
 
 
-        }catch (\Exception $e) {
+        } catch (\Exception $e) {
             // 处理异常
             // 处理异常
             @file_put_contents('quanju4.txt', json_encode(['line' => $e->getLine(), 'message' => $e->getMessage(), 'file' => $e->getFile()]) . "-会员等级激励奖报错内容\r\n", 8);
             @file_put_contents('quanju4.txt', json_encode(['line' => $e->getLine(), 'message' => $e->getMessage(), 'file' => $e->getFile()]) . "-会员等级激励奖报错内容\r\n", 8);
 
 
@@ -1045,7 +1226,7 @@ class StoreOrder extends BaseModel
                 User::where('uid', $one_spread_info['uid'])->update(['brokerage_price' => $blance]);
                 User::where('uid', $one_spread_info['uid'])->update(['brokerage_price' => $blance]);
 
 
             }
             }
-            $price=0;
+            $price = 0;
             //然后算二级推荐人的
             //然后算二级推荐人的
             if ($userInfo['agent'] > 0 && $two_spread_info) {
             if ($userInfo['agent'] > 0 && $two_spread_info) {
                 if ($two_spread_info['agent'] > 0) {
                 if ($two_spread_info['agent'] > 0) {
@@ -1055,7 +1236,7 @@ class StoreOrder extends BaseModel
                         }
                         }
                     } elseif ($two > $one) {  //如果二级推荐人等级大于直推等级
                     } elseif ($two > $one) {  //如果二级推荐人等级大于直推等级
                         if ($two > $user_agnet['grade']) {  //如果二级推荐人等级高于自己
                         if ($two > $user_agnet['grade']) {  //如果二级推荐人等级高于自己
-                            $indirect_rebates = bcmul($two_agent['indirect_rebates'],2,2);
+                            $indirect_rebates = bcmul($two_agent['indirect_rebates'], 2, 2);
                             $price = bcmul($order['total_price'], bcdiv($indirect_rebates, 100, 2), 2); //二级推荐人获得直接推荐比例的两倍
                             $price = bcmul($order['total_price'], bcdiv($indirect_rebates, 100, 2), 2); //二级推荐人获得直接推荐比例的两倍
 
 
                         } elseif ($two == $user_agnet['grade']) {  //如果二级推荐人等级等于自己
                         } elseif ($two == $user_agnet['grade']) {  //如果二级推荐人等级等于自己
@@ -1070,34 +1251,36 @@ class StoreOrder extends BaseModel
                 }
                 }
             }
             }
             return true;
             return true;
-        }catch (\Exception $e) {
+        } catch (\Exception $e) {
             // 处理异常
             // 处理异常
             @file_put_contents('quanju4.txt', json_encode(['line' => $e->getLine(), 'message' => $e->getMessage(), 'file' => $e->getFile()]) . "-代理等级批发返利报错内容\r\n", 8);
             @file_put_contents('quanju4.txt', json_encode(['line' => $e->getLine(), 'message' => $e->getMessage(), 'file' => $e->getFile()]) . "-代理等级批发返利报错内容\r\n", 8);
 
 
             return false;
             return false;
         }
         }
     }
     }
+
 //伞下返利
 //伞下返利
-    public static function umbrella($order){
-        try{
+    public static function umbrella($order)
+    {
+        try {
 //        获取所有伞下比例大于0的等级
 //        获取所有伞下比例大于0的等级
-            $agent_level = SystemUserLevel::where('umbrella_rebates','>',0)->where('is_show',1)->where('is_del',0)->column('id');
+            $agent_level = SystemUserLevel::where('umbrella_rebates', '>', 0)->where('is_show', 1)->where('is_del', 0)->column('id');
 
 
 //        for循环所有伞下比例大于0的等级计算他们每个等级伞下比例乘订单金额的奖池数量再除以该等级的上级人数
 //        for循环所有伞下比例大于0的等级计算他们每个等级伞下比例乘订单金额的奖池数量再除以该等级的上级人数
-            foreach ($agent_level as $level){
+            foreach ($agent_level as $level) {
                 $level_uids = self::getAllSuperiors($order['uid'], $level['id']); //获取所有符合等级的上级用户UID
                 $level_uids = self::getAllSuperiors($order['uid'], $level['id']); //获取所有符合等级的上级用户UID
                 $level_count = count($level_uids); //符合等级的上级人数
                 $level_count = count($level_uids); //符合等级的上级人数
-                $pool = bcmul($order['total_price'],bcdiv($level['umbrella_rebates'],100,2),2); //该等级奖池
-                $user_price = bcdiv($pool,$level_count,2); //该等级奖池/符合等级的上级人数
-                $name = SystemUserLevel::where('id',$level['id'])->value('name'); //等级名称
+                $pool = bcmul($order['total_price'], bcdiv($level['umbrella_rebates'], 100, 2), 2); //该等级奖池
+                $user_price = bcdiv($pool, $level_count, 2); //该等级奖池/符合等级的上级人数
+                $name = SystemUserLevel::where('id', $level['id'])->value('name'); //等级名称
                 foreach ($level_uids as $uid) {
                 foreach ($level_uids as $uid) {
                     $brokerage_price = User::where('uid', $uid)->value('brokerage_price');
                     $brokerage_price = User::where('uid', $uid)->value('brokerage_price');
                     $blance = bcadd($brokerage_price, $user_price, 2);
                     $blance = bcadd($brokerage_price, $user_price, 2);
-                    UserBill::income('伞下团体返利', $uid, 'brokerage_price', 'umbrella_rebates', $user_price, $order['id'], $blance, $name.'伞下团队购买商品返利');
+                    UserBill::income('伞下团体返利', $uid, 'brokerage_price', 'umbrella_rebates', $user_price, $order['id'], $blance, $name . '伞下团队购买商品返利');
                     User::where('uid', $uid)->update(['brokerage_price' => $blance]);
                     User::where('uid', $uid)->update(['brokerage_price' => $blance]);
                 }
                 }
             }
             }
-        }catch (\Exception $e) {
+        } catch (\Exception $e) {
             // 处理异常
             // 处理异常
             @file_put_contents('quanju4.txt', json_encode(['line' => $e->getLine(), 'message' => $e->getMessage(), 'file' => $e->getFile()]) . "-伞下团队批发返利报错内容\r\n", 8);
             @file_put_contents('quanju4.txt', json_encode(['line' => $e->getLine(), 'message' => $e->getMessage(), 'file' => $e->getFile()]) . "-伞下团队批发返利报错内容\r\n", 8);
 
 
@@ -1105,6 +1288,7 @@ class StoreOrder extends BaseModel
         }
         }
         return true;
         return true;
     }
     }
+
     /**
     /**
      * 递归获取所有上级(推荐人/推广人)的UID
      * 递归获取所有上级(推荐人/推广人)的UID
      * @param int $uid 团队成员的ID
      * @param int $uid 团队成员的ID
@@ -1112,7 +1296,8 @@ class StoreOrder extends BaseModel
      * @param array $allSuperiors 内部递归使用,用于存储所有上级UID,初始为空数组
      * @param array $allSuperiors 内部递归使用,用于存储所有上级UID,初始为空数组
      * @return array 过滤后的上级UID列表
      * @return array 过滤后的上级UID列表
      */
      */
-    public static function getAllSuperiors($uid, $agent = null, &$allSuperiors = []) {
+    public static function getAllSuperiors($uid, $agent = null, &$allSuperiors = [])
+    {
         // 1. 获取当前用户的直接上级 spread_uid
         // 1. 获取当前用户的直接上级 spread_uid
         // 假设 User::where('uid', $uid)->value('spread_uid') 可以获取到该用户的直接上级ID
         // 假设 User::where('uid', $uid)->value('spread_uid') 可以获取到该用户的直接上级ID
         $superiorUid = User::where('uid', $uid)->value('spread_uid');
         $superiorUid = User::where('uid', $uid)->value('spread_uid');
@@ -1146,6 +1331,7 @@ class StoreOrder extends BaseModel
         // 7. 如果没有传入 $agent,则返回所有收集到的上级 UID
         // 7. 如果没有传入 $agent,则返回所有收集到的上级 UID
         return $resultUids;
         return $resultUids;
     }
     }
+
     /*
     /*
      * 线下支付消息通知
      * 线下支付消息通知
      * 待完善
      * 待完善

+ 46 - 49
app/models/store/StoreProductLevel.php

@@ -17,76 +17,73 @@ use crmeb\traits\ModelTrait;
  * Class StoreProductAttr
  * Class StoreProductAttr
  * @package app\models\store
  * @package app\models\store
  */
  */
-class StoreProductAttr extends BaseModel
+class StoreProductLevel extends BaseModel
 {
 {
     /**
     /**
      * 模型名称
      * 模型名称
      * @var string
      * @var string
      */
      */
-    protected $name = 'store_product_attr';
+    protected $name = 'store_product_level';
 
 
     use ModelTrait;
     use ModelTrait;
+    protected $autoWriteTimestamp = true;
 
 
-    protected function getAttrValuesAttr($value)
-    {
-        return explode(',',$value);
-    }
-
-    public static function storeProductAttrValueDb()
-    {
-        return Db::name('StoreProductAttrValue');
-    }
+    protected $createTime = 'add_time';
 
 
+    protected $updateTime = 'update_time';
 
 
     /**
     /**
-     * 获取商品属性数据
-     * @param $productId
+     * 获取商品的等级返利数据
+     * @param int $productId 商品ID
      * @return array
      * @return array
      */
      */
-    public static function getProductAttrDetail($productId,$uid=0,$type = 0,$type_id=0)
+    public static function getProductLevelRebate($productId)
     {
     {
-        $attrDetail = self::where('product_id',$productId)->where('type',$type_id)->order('id asc')->select()->toArray()?:[];
-        $_values = self::storeProductAttrValueDb()->where('product_id',$productId)->where('type',$type_id)->select();
-        $values = [];
-        foreach ($_values as $value){
-            if($type){
-                if ($uid)
-                    $value['cart_num'] = StoreCart::where('product_attr_unique',$value['unique'])->where('is_pay', 0)->where('is_del', 0)->where('is_new', 0)->where('type', 'product')->where('product_id', $productId)->where('uid', $uid)->value('cart_num');
-                else
-                    $value['cart_num'] = 0;
-                if (is_null($value['cart_num'])) $value['cart_num'] = 0;
-            }
-            $values[$value['suk']] = $value;
-        }
-        foreach ($attrDetail as $k=>$v){
-            $attr = $v['attr_values'];
-//            unset($productAttr[$k]['attr_values']);
-            foreach ($attr as $kk=>$vv){
-                $attrDetail[$k]['attr_value'][$kk]['attr'] =  $vv;
-                $attrDetail[$k]['attr_value'][$kk]['check'] =  false;
-            }
-        }
-        return [$attrDetail,$values];
+        return self::where('product_id', $productId)->select()->toArray();
     }
     }
 
 
-    public static function uniqueByStock($unique)
+    /**
+     * 根据等级ID获取返利比例
+     * @param int $productId 商品ID
+     * @param int $levelId 等级ID
+     * @return float|int
+     */
+    public static function getRebateRatio($productId, $levelId)
     {
     {
-        return self::storeProductAttrValueDb()->where('unique',$unique)->value('stock')?:0;
+        $rebate = self::where('product_id', $productId)->where('level_id', $levelId)->value('rebate_ratio');
+        return $rebate !== null ? $rebate : 0;
     }
     }
 
 
-    public static function uniqueByAttrInfo($unique, $field = '*')
+    /**
+     * 批量保存商品等级返利数据
+     * @param int $productId 商品ID
+     * @param array $levelRebates 等级返利数据
+     * @return bool
+     */
+    public static function saveProductLevelRebate($productId, $levelRebates)
     {
     {
-        return self::storeProductAttrValueDb()->field($field)->where('unique',$unique)->find();
-    }
+        // 开启事务
+        self::beginTrans();
+        try {
+            // 删除原有数据
+            self::where('product_id', $productId)->delete();
 
 
-    public static function issetProductUnique($productId,$unique)
-    {
-//        $res = self::be(['product_id'=>$productId]);
-        $res = self::where('product_id',$productId)->where('type',0)->find();
-        if($unique){
-            return $res && self::storeProductAttrValueDb()->where('product_id',$productId)->where('unique',$unique)->where('type',0)->count() > 0;
-        }else{
-            return !$res;
+            // 插入新数据
+            foreach ($levelRebates as $level) {
+                self::create([
+                    'product_id' => $productId,
+                    'level_id' => $level['id'],
+                    'rebate_ratio' => $level['rebate_ratio'],
+                ]);
+            }
+
+            // 提交事务
+            self::commitTrans();
+            return true;
+        } catch (\Exception $e) {
+            // 回滚事务
+            self::rollbackTrans();
+            return false;
         }
         }
     }
     }