Browse Source

新会员等级

gorden 4 months ago
parent
commit
100f0f1da9

+ 67 - 0
app/admin/controller/goods/MemberRechargeBenefitController.php

@@ -0,0 +1,67 @@
+<?php
+
+namespace app\admin\controller\goods;
+
+use app\admin\service\goods\GoodsService;
+use app\admin\service\goods\MemberRechargeBenefitService;
+use app\admin\service\goods\PartnerService;
+use app\admin\validate\goods\GoodsValidate;
+use support\Request;
+use support\Response;
+
+class MemberRechargeBenefitController
+{
+    /**
+     * @Desc 列表
+     * @Author Gorden
+     * @Date 2024/3/28 10:08
+     *
+     * @param Request $request
+     * @return Response
+     */
+    public function select(Request $request)
+    {
+
+        return MemberRechargeBenefitService::select($request, 'RECHARGE');
+    }
+
+    public function selectCascaderList(Request $request)
+    {
+        return MemberRechargeBenefitService::selectCascaderList($request);
+    }
+
+    /**
+     * @Desc 商品详情
+     * @Author Gorden
+     * @Date 2024/3/28 10:25
+     *
+     * @param Request $request
+     * @return Response
+     */
+    public function info(Request $request)
+    {
+        $validate = new GoodsValidate();
+        if (!$validate->scene('info')->check($request->get())) {
+            return json_fail($validate->getError());
+        }
+
+        return MemberRechargeBenefitService::info($request->get('goods_id'));
+    }
+
+    /**
+     * @Desc 修改商品
+     * @Author Gorden
+     * @Date 2024/3/28 13:22
+     *
+     * @param Request $request
+     * @return Response
+     */
+    public function update(Request $request): Response
+    {
+        $validate = new GoodsValidate();
+        if (!$validate->scene('update')->check($request->post())) {
+            return json_fail($validate->getError());
+        }
+        return MemberRechargeBenefitService::update($request->post());
+    }
+}

+ 15 - 7
app/admin/controller/notify/RechargeController.php

@@ -113,29 +113,35 @@ class RechargeController
             $payDetail->save();
             // 赠送比例
             $objectJson = json_decode($payDetail->join_pay_object_json, true);
-            $addedNbr = 0;
+            $goodsAttributeJson = [];
             if (isset($objectJson['order_id'])) {
                 // 对应订单设置已完成
                 Order::where('order_groupby', $payDetail->join_pay_order_id)->update(['order_status_system' => 'DONE', 'order_is_complete' => 'Y', 'order_status_storage' => 'DONE']);
-                $addedNbr = RechargeService::disposeOrder($objectJson['order_id']);
-
-
-                // throw new BusinessException("支付数据异常");
-//                return json_fail("");
+                $goodsAttributeJson = RechargeService::getGoodsAttributeJson($objectJson['order_id']);
             }
             // 赠送金额累加到 账户表 member_account_added
             $memberAccount = MemberAccount::where('join_account_member_id', $payDetail->join_pay_member_id)
                 ->where('member_account_classify', 'CASH')
                 ->first();
+            $addedNbr = $goodsAttributeJson['added'] && $goodsAttributeJson['added']['nbr'] ? $goodsAttributeJson['added']['nbr'] : 0;
             $payAmount = floatval($payDetail->pay_amount);
-            $added = $memberAccount->member_account_added + $payAmount * $addedNbr;
+            $addedAmount = $payAmount * $addedNbr;
+            $added = $memberAccount->member_account_added + $addedAmount;
             $income = $memberAccount->member_account_income + $payAmount;
+            // 保留原数据
+            RechargeService::saveOriginData($memberAccount, $payAmount,$addedNbr, $addedAmount);
+
             $memberAccount->member_account_added = $added;
             $memberAccount->member_account_income = $income;
             $memberAccount->member_account_surplus = $memberAccount->member_account_surplus + $payAmount;
             $memberAccount->save();
 
             // 根据最新的数据,更新用户等级
+            RechargeService::disposeRole($payDetail->join_pay_member_id, $payDetail->pay_amount);
+
+            // 发券
+            RechargeService::disposeRoleCoupon($goodsAttributeJson,$payDetail->join_pay_member_id);
+
             // 临时屏蔽该会员升级
 //            if (!in_array($payDetail->join_pay_member_id, ['MR2409132254Z9VW'])) {
 //                $member = Member::find($payDetail->join_pay_member_id);
@@ -148,6 +154,8 @@ class RechargeController
 //                }
 //            }
 
+
+
             // 计算充值提成
             if (!empty($payDetail->join_pay_object_json)) {
                 $payObjectJson = json_decode($payDetail->join_pay_object_json, true);

+ 2 - 0
app/admin/controller/order/PayDetailController.php

@@ -511,12 +511,14 @@ class PayDetailController extends Curd
                 'order_category' => 'RECHARGE',
                 'order_status_system' => 'PAYING',
                 'order_status_storage' => 'PENDING',
+                'order_config_json' => json_encode(['order_category' => 'RECHARGE']),
                 'order_addtimes' => time()
             ];
             if ($type == 'WELFARE') {
                 $orderData['order_is_complete'] = 'Y';
                 $orderData['order_status_system'] = 'DONE';
                 $orderData['order_status_storage'] = 'DONE';
+                unset($orderData['order_config_json']);
             }
             $sku = GoodsSku::where('join_sku_goods_id', $params['goods_id'])->first();
 

+ 1171 - 0
app/admin/controller/order/RechargeController.php

@@ -0,0 +1,1171 @@
+<?php
+
+namespace app\admin\controller\order;
+
+use app\admin\service\coupon\CouponService;
+use app\admin\service\member\MemberService;
+use app\admin\service\order\OrderService;
+use app\admin\validate\order\OrderValidate;
+use app\controller\Curd;
+use app\model\Appointment;
+use app\model\ClientConfig;
+use app\model\Coupon;
+use app\model\Goods;
+use app\model\GoodsComponent;
+use app\model\GoodsRunning;
+use app\model\GoodsSku;
+use app\model\Member;
+use app\model\MemberAccount;
+use app\model\MemberBenefit;
+use app\model\MemberRole;
+use app\model\Order;
+use app\model\OrderExpress;
+use app\model\OrderReturn;
+use app\model\OrderSheet;
+use app\model\PayDetail;
+use app\model\Supplier;
+use app\model\SysDept;
+use app\model\SysUser;
+use support\Db;
+use support\exception\BusinessException;
+use support\Redis;
+use support\Request;
+use support\Response;
+use Webman\Event\Event;
+use Yansongda\Pay\Pay;
+
+class RechargeController extends Curd
+{
+    public function __construct()
+    {
+        $this->model = new Order();
+        $this->validate = true;
+        $this->validateClass = new OrderValidate();
+    }
+
+    /**
+     * @Desc 列表
+     * @Author Gorden
+     * @Date 2024/3/28 15:01
+     *
+     * @param Request $request
+     * @return Response
+     * @throws \support\exception\BusinessException
+     */
+    public function select(Request $request): Response
+    {
+        [$where, $format, $limit, $field, $order] = $this->selectInput($request);
+        $where['order_classify'] = 'RECHARGE';
+        if (!empty($where['order_addtimes'])) {
+            $where['order_addtimes'][0] = strtotime($where['order_addtimes'][0]);
+            $where['order_addtimes'][1] = strtotime($where['order_addtimes'][1]);
+        }
+
+        $order = $request->get('order', 'desc');
+        $field = $field ?? 'order_addtimes';
+        $orderIds = [];
+        if (!empty($orderId)) {
+            $orderIds = Order::where('order_id', 'like', '%' . $orderId . '%')
+                ->where('order_classify', 'RECHARGE')
+                ->pluck('order_id')
+                ->toArray();
+        }
+        $goodsName = trim($request->get('goods_name', ''));
+        if (!empty($goodsName)) {
+            $goodsIds = Goods::where('goods_classify', 'RECHARGE')
+                ->where('goods_name', 'like', '%' . $goodsName . '%')
+                ->pluck('goods_id')
+                ->toArray();
+            $goodsOrderIds = OrderSheet::whereIn('join_sheet_goods_id', $goodsIds)->pluck('join_sheet_order_id')->toArray();
+            if (!empty($where['order_id'])) {
+                $orderIds = array_intersect($orderIds, $goodsOrderIds);
+            } else {
+                $orderIds = $goodsOrderIds;
+            }
+        }
+        if (!empty($orderId) || !empty($goodsName)) {
+            $where['order_id'] = ['in', implode(',', $orderIds)];
+        }
+
+        $query = $this->doSelect($where, $field, $order);
+        return $this->doFormat($query, $format, $limit);
+    }
+
+    protected function doSelect(array $where, string $field = null, string $order = 'desc')
+    {
+        $model = $this->model->with([
+            'sheets' => function ($query) {
+                $query->select('join_sheet_order_id', 'order_sheet_id', 'join_sheet_goods_id', 'order_sheet_num', 'order_sheet_price');
+            },
+            'member' => function ($query) {
+                $query->select('member_id', 'member_mobile');
+            },
+            'cert' => function ($query) {
+                $query->select('join_cert_member_id', 'member_cert_name');
+            },
+//            'return' => function ($query) use ($where){
+//                if (isset($where['return'])){
+//                    dump($where['return']);
+//                    $query = $query->where('order_return_status',$where['return']);
+//                }
+//                $query->select('orders_return_id', 'join_return_order_id', 'order_return_status');
+//            },
+            // 'express' => function ($query) {
+            //     $query->select('join_express_order_id', 'order_express_type');
+            // }
+        ])->leftJoin('order_return', 'order_return.join_return_order_id', '=', 'order.order_id')
+            ->leftJoin('order_express', 'order_express.join_express_order_id', '=', 'order.order_id');
+        // ->leftJoin('order_sheet','join_sheet_order_id','=','order.order_id');
+        foreach ($where as $column => $value) {
+            if (is_array($value)) {
+                if ($value[0] === 'like' || $value[0] === 'not like') {
+                    $model = $model->where($column, $value[0], "%$value[1]%");
+                } elseif (in_array($value[0], ['>', '=', '<', '<>'])) {
+                    $model = $model->where($column, $value[0], $value[1]);
+                } elseif ($value[0] == 'in' && !empty($value[1])) {
+                    $valArr = $value[1];
+                    if (is_string($value[1])) {
+                        $valArr = explode(",", trim($value[1]));
+                    }
+                    $model = $model->whereIn($column, $valArr);
+                } elseif ($value[0] == 'not in' && !empty($value[1])) {
+                    $valArr = $value[1];
+                    if (is_string($value[1])) {
+                        $valArr = explode(",", trim($value[1]));
+                    }
+                    $model = $model->whereNotIn($column, $valArr);
+                } elseif ($value[0] == 'null') {
+                    $model = $model->whereNull($column);
+                } elseif ($value[0] == 'not null') {
+                    $model = $model->whereNotNull($column);
+                } elseif ($value[0] !== '' || $value[1] !== '') {
+                    $model = $model->whereBetween($column, $value);
+                }
+            } else {
+                $model = $model->where($column, $value);
+            }
+        }
+        if ($field) {
+            $model = $model->orderBy($field, $order);
+        }
+        $model = $model->whereJsonContains('order_config_json->order_category', 'RECHARGE')
+            ->select('order.*', 'order_express.join_express_order_id', 'order_express.order_express_type', 'order_return.orders_return_id', 'order_return.join_return_order_id', 'order_return.order_return_status', 'order_return.order_return_apply_json', 'order_return.order_return_remark');
+        return $model;
+    }
+
+    public function afterQuery($items)
+    {
+        foreach ($items as &$item) {
+            $sheetDeng = '';
+            $item['sheet'] = $item['sheets'][0] ?? [];
+            if (!empty($item['sheet'])) {
+                $goods = Goods::where('goods_id', $item['sheet']['join_sheet_goods_id'])->first();
+                if (count($item['sheets']) > 1 && $goods->goods_classify == 'MEALS') {
+                    $sheetDeng = ' 等餐品';
+                }
+                $item['sheet']['goods_name'] = ($goods && $goods->goods_name) ? $goods->goods_name . $sheetDeng : '';
+                $item['sheet']['goods_classify'] = $goods->goods_classify ?? '';
+                $item['sheet']['order_sheet_num'] = intval($item['sheet']['order_sheet_num']);
+            }
+            unset($item['sheets']);
+            if (isset($item['orders_return_id'])) {
+                $item['return'] = [
+                    'orders_return_id' => $item['orders_return_id'],
+                    'join_return_order_id' => $item['join_return_order_id'],
+                    'order_return_status' => $item['order_return_status'],
+                    'order_return_apply_json' => $item['order_return_apply_json'],
+                    'order_return_remark' => $item['order_return_remark']
+                ];
+            }
+            if (isset($item['join_express_order_id'])) {
+                $item['express'] = [
+                    'join_express_order_id' => $item['join_express_order_id'],
+                    'order_express_type' => $item['order_express_type']
+                ];
+                unset($item['join_express_order_id'], $item['order_express_type']);
+            }
+            // if (!empty($item['order_extend_json'])){
+            //     $orderExtendJson = json_decode($item['order_extend_json'],true);
+            //     $item['referee'] = $orderExtendJson['referee'] ?? '';
+            // }
+        }
+
+        return $items;
+    }
+
+    /**
+     * @Desc 下单+支付
+     * @Author Gorden
+     * @Date 2024/9/5 13:13
+     *
+     * @param Request $request
+     * @return Response
+     */
+    public function insert(Request $request): Response
+    {
+        $params = $request->post();
+        // 判断餐品是否连带着服务或实体
+        $goodsClassifys = array_unique(array_column($params['goodsContentList'], 'goods_classify'));
+        $params['goods_classify'] = $goodsClassifys[0];
+        $orderExtendJson = [];
+        Db::beginTransaction();
+        try {
+            // 验证线下付款密码
+            if ($params['settlement_now'] == 'Y' && $params['pay_constitute'] == 'N' && in_array($params['pay_category'], ['OFFLINE', 'MONEY'])) {
+                $password = $params['offline_password'];
+                if ($password != '666888') {
+                    throw new BusinessException('密码错误,请重新输入');
+                }
+            }
+            // 下单账户
+            if (empty($params['join_order_member_id']) && !empty($params['mobile'])) {
+                if (Member::where('member_mobile', $params['mobile'])->exists()) {
+                    throw new BusinessException('会员已存在');
+                }
+                $params['join_order_member_id'] = $params['member_id'] = 'MR' . date('ymdHi') . random_string(4, 'up');
+                // 创建会员
+                MemberService::createMember($params);
+            } else if (empty($params['join_order_member_id']) && empty($params['mobile'])) {
+                $params['join_order_member_id'] = Member::where('member_mobile', '0000')->value('member_id');
+            }
+            if (empty($params['join_order_member_id'])) {
+                throw new BusinessException('检查下单账户');
+            }
+
+            $params['orderId'] = 'OD' . date('ymdHi') . random_string(4, 'up');
+            $params['orderGroupId'] = 'OD' . date('ymdHi') . random_string(4, 'up');
+            $systemStatus = 'PAYING';
+            // 立即结算
+            if ($params['settlement_now'] == 'Y') {
+                if ($params['goods_classify'] == 'RECHARGE') {
+                    $params['order_is_complete'] = 'Y';
+                    $systemStatus = 'DONE';
+                }
+            }
+
+            if ($params['settlement_now'] == 'Y' && ($params['pay_category'] == 'OFFLINE' || $params['pay_category'] == 'MONEY')) {
+                if ($params['pay_category'] == 'OFFLINE' && !empty($params['pay_category_sub'])) {
+                    $params['pay_category'] = $params['pay_category_sub'];
+                }
+                $params['order_status_system'] = $systemStatus;
+                $params['order_status_payment'] = 'SUCCESS';
+            }
+            if ($params['pay_category'] == 'QRCODE' && $params['settlement_now'] == 'Y' && !empty($params['qrcode_nbr'])) {     // 付款码
+                $result = OrderService::qrcodePay($params);
+                $result = json_encode($result);
+                $params['pay_json_response'] = $result;
+                $result = json_decode($result, true);
+
+                $prefix = substr($params['qrcode_nbr'], 0, 2);
+                if (in_array($prefix, [10, 11, 12, 13, 14, 15])) {
+                    $params['pay_category'] = 'WXPAY';
+                    if ((!isset($result['return_code']) || $result['return_code'] != 'SUCCESS') || (!isset($result['result_code']) || $result['result_code'] != 'SUCCESS') || (empty($result['trade_state']) || $result['trade_state'] != 'SUCCESS')) {
+                        $params['order_status_system'] = 'PAYING';
+                        $params['order_status_payment'] = 'PENDING';
+                        $params['order_is_complete'] = 'N';
+                    } else {
+                        $params['order_status_system'] = $systemStatus;
+                        $params['order_status_payment'] = 'SUCCESS';
+                    }
+                } else if (in_array($prefix, [25, 26, 27, 28, 29, 30])) {
+                    $params['pay_category'] = 'ALIPAY';
+                    if ((!isset($result['code']) || $result['code'] != '10000') || (empty($result['trade_status']) || $result['trade_status'] != 'TRADE_SUCCESS')) {
+                        $params['order_status_system'] = 'PAYING';
+                        $params['order_status_payment'] = 'PENDING';
+                        $params['order_is_complete'] = 'N';
+                    } else {
+                        $params['order_status_system'] = $systemStatus;
+                        $params['order_status_payment'] = 'SUCCESS';
+                    }
+                } else {
+                    throw new BusinessException('付款码无效');
+                }
+            }
+
+            $params['order_extend_json'] = $orderExtendJson;
+            // 写入主订单
+            $this->insertMain($params);
+            // 订单详情
+            $this->insertSheet($params);
+
+            // 支付记录
+            $payId = $this->insertPayDetail($params);
+            Db::commit();
+            if ($params['order_status_payment'] == 'SUCCESS') {
+                // 入收支明细表
+                $params['inout_category'] = '会员充值订单收入';
+                Event::dispatch('statistics.inout.in', $params);
+
+                // 充值回调
+                (new \app\admin\controller\notify\RechargeController)->disposePaySuccess($payId);
+            }
+            if ($params['settlement_now'] == 'Y' && $params['order_status_payment'] != 'SUCCESS') {
+                _syslog("订单", "支付异常,检查是否有轮询");
+                return json_throw(2001, '支付异常', ['order_id' => $params['orderId'], 'group_id' => $params['orderGroupId']]);
+            }
+            _syslog("订单", "创建订单成功");
+            return json_success('创建订单成功');
+        } catch (BusinessException $e) {
+            Db::rollBack();
+            dump($e->getMessage());
+            dump($e->getTrace());
+            _syslog("订单", $e->getMessage());
+            return json_fail($e->getMessage());
+        } catch (\Exception $e) {
+            Db::rollBack();
+            dump($e->getMessage());
+            dump($e->getTrace());
+            _syslog("订单", "创建订单失败");
+            return json_fail('创建订单失败');
+        }
+    }
+
+    /**
+     * @Desc 支付
+     * @Author Gorden
+     * @Date 2024/9/5 13:12
+     *
+     * @param Request $request
+     * @return Response
+     */
+    public function pay(Request $request)
+    {
+        $params = $request->post();
+        // 验证线下付款密码
+        if ($params['pay_constitute'] == 'N' && in_array($params['pay_category'], ['OFFLINE', 'MONEY'])) {
+            $password = $params['offline_password'];
+            if ($password != '666888') {
+                return json_fail("密码错误,请重新输入");
+            }
+        }
+
+        $order = Order::where('order_id', $params['order_id'])->first();
+        if (!$order) {
+            return json_fail('订单异常');
+        }
+        if ($order->order_status_system != 'PAYING') {
+            return json_fail('订单不是可支付状态');
+        }
+
+        $params['orderId'] = $params['order_id'];
+
+        $params['orderGroupId'] = 'OD' . date('ymdHi') . random_string(4, 'up');
+        $order->order_groupby = $params['orderGroupId'];
+
+        $goods = Goods::where('goods_id', $params['join_sheet_goods_id'])
+            ->select('goods_id', 'goods_name', 'goods_classify')
+            ->first();
+        if (!$goods) {
+            return json_fail('产品数据异常');
+        }
+        $goods = $goods->toArray();
+        $params['goods_classify'] = $goods['goods_classify'] ?? '';
+        // 入伙场所
+        if (!empty($params['dept_id'])) {
+            $orderExtendJson = [];
+            if (!empty($order->order_extend_json)) {
+                $orderExtendJson = json_decode($order->order_extend_json, true);
+            }
+            $dept = SysDept::where('dept_id', $params['dept_id'])->first();
+            if (!$dept) {
+                throw new BusinessException("入伙场所不存在");
+            }
+            $params['dept_name'] = $dept->dept_name;
+            $orderExtendJson['dept_id'] = $params['dept_id'];
+            $orderExtendJson['dept_name'] = $params['dept_name'];
+            $order->order_extend_json = json_encode($orderExtendJson);
+        }
+        // 立即结算
+        if ($params['goods_classify'] == 'RECHARGE') {
+            $order->order_is_complete = 'Y';
+            $systemStatus = 'DONE';
+        }
+        $paymentStatus = 'PENDING';
+        Db::beginTransaction();
+        try {
+            // 组合支付时,付款码应收金额
+            $qrcodePayAmount = 0;
+            if ($params['pay_category'] == 'OFFLINE' || $params['pay_category'] == 'MONEY') {
+                $order->order_status_system = $systemStatus;
+                $order->order_status_payment = 'SUCCESS';
+                $paymentStatus = 'SUCCESS';
+                if ($params['pay_category'] == 'OFFLINE' && !empty($params['pay_category_sub'])) {
+                    $params['pay_category'] = $params['pay_category_sub'];
+                }
+            }
+            if (($params['pay_constitute'] == 'Y' || $params['pay_category'] == 'QRCODE') && !empty($params['qrcode_nbr'])) {     // 付款码
+                // 提交过来的支付分类
+                $submitPayCategory = $params['pay_category'];
+                // 账户支付的金额
+                $accountAmount = $params['order_amount_pay'];
+                if ($params['pay_constitute'] == 'Y' && $qrcodePayAmount > 0) {
+                    // 组合支付,改成需要付款码需要支付的金额
+                    $params['order_amount_pay'] = $qrcodePayAmount;
+                }
+                // 去支付
+                $result = OrderService::qrcodePay($params);
+                $result = json_encode($result);
+                $params['pay_json_response'] = $result;
+                $result = json_decode($result, true);
+
+                $prefix = substr($params['qrcode_nbr'], 0, 2);
+                if (in_array($prefix, [10, 11, 12, 13, 14, 15])) {
+                    $params['pay_category'] = 'WXPAY';
+                    if ((!isset($result['return_code']) || $result['return_code'] != 'SUCCESS') || (!isset($result['result_code']) || $result['result_code'] != 'SUCCESS') || (empty($result['trade_state']) || $result['trade_state'] != 'SUCCESS')) {
+                        $order->order_status_system = 'PAYING';
+                        $order->order_status_payment = 'PENDING';
+                        $order->order_is_complete = 'N';
+//                        Db::rollBack();
+//                        return json_fail('支付失败');
+                    } else {
+                        $order->order_status_system = $systemStatus;
+                        $order->order_status_payment = 'SUCCESS';
+                        $paymentStatus = 'SUCCESS';
+                    }
+                } else if (in_array($prefix, [25, 26, 27, 28, 29, 30])) {
+                    $params['pay_category'] = 'ALIPAY';
+                    if ((!isset($result['code']) || $result['code'] != '10000') || (empty($result['trade_status']) || $result['trade_status'] != 'TRADE_SUCCESS')) {
+                        $order->order_status_system = 'PAYING';
+                        $order->order_status_payment = 'PENDING';
+                        $order->order_is_complete = 'N';
+//                        Db::rollBack();
+//                        return json_fail('支付失败');
+                    } else {
+                        $order->order_status_system = $systemStatus;
+                        $order->order_status_payment = 'SUCCESS';
+                        $paymentStatus = 'SUCCESS';
+                    }
+                } else {
+                    throw new BusinessException('付款码无效');
+                }
+
+                // 账户支付的金额
+                $params['order_amount_pay'] = $accountAmount;
+            }
+            if ($order->order_status_payment == 'SUCCESS') {
+                $order->order_is_complete = 'Y';
+            }
+
+            // 主订单
+            $order->save();
+
+            // sheet
+            if ($order->order_status_payment == 'SUCCESS') {
+                $data = [
+                    'order_sheet_status' => $systemStatus
+                ];
+                if (floatval($order->order_amount_paid) < $order->order_amount_total) {
+                    $data['order_sheet_status'] = 'BEING';
+                }
+                OrderSheet::where('join_sheet_order_id', $params['order_id'])->update($data);
+            }
+
+            // 清除此订单的未支付记录
+            PayDetail::whereJsonContains('join_pay_object_json->order_id', $order->order_id)->where('pay_status', 'WAITING')->delete();
+            // 重新创建
+            $payId = $this->insertPayDetail($params);
+
+            Db::commit();
+            if ($order->order_status_payment == 'SUCCESS') {
+                // 入收支明细表
+                $params['inout_category'] = '会员充值订单收入';
+                Event::dispatch('statistics.inout.in', $params);
+
+                // 充值回调
+                (new \app\admin\controller\notify\RechargeController)->disposePaySuccess($payId);
+            }
+            if ($order->order_status_payment != 'SUCCESS' && $paymentStatus != 'SUCCESS') {
+                _syslog("订单", "支付异常,检查是否有轮询");
+                return json_throw(2001, '支付异常', ['order_id' => $params['orderId'], 'group_id' => $params['orderGroupId']]);
+            }
+            _syslog("订单", "订单支付成功");
+            return json_success('支付成功');
+        } catch (BusinessException $e) {
+            dump($e->getMessage());
+            Db::rollBack();
+            _syslog("订单", "订单支付失败:" . $e->getMessage());
+            return json_fail("支付失败:" . $e->getMessage());
+        } catch (\Exception $e) {
+            dump($e->getMessage());
+            Db::rollBack();
+            _syslog("订单", "订单支付失败");
+            return json_fail('支付失败');
+        }
+    }
+
+    /**
+     * @Desc
+     * @Author Gorden
+     * @Date 2024/6/7 10:30
+     *
+     * @param $params
+     * @return void
+     * @throws BusinessException
+     */
+    public function insertMain($params)
+    {
+        try {
+            $orderCategory = 'NORMAL';
+            if (!empty($params['order_category'])) {
+                $orderCategory = $params['order_category'];
+            } else if (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') {
+                $orderCategory = 'DISHES';
+            } else if (isset($params['goods_classify'])) {
+                $orderCategory = $params['goods_classify'];
+            }
+            if (empty($params['order_extend_json'])) {
+                $params['order_extend_json'] = [];
+            } else {
+                if (is_json($params['order_extend_json'])) {
+                    $params['order_extend_json'] = json_decode($params['order_extend_json'], true);
+                }
+            }
+            // 推荐人
+            $params['order_extend_json']['referee'] = $params['referee'] ?? '';
+
+            $data = [
+                'order_id' => $params['orderId'],
+                'order_groupby' => $params['orderGroupId'],
+                'join_order_member_id' => $params['join_order_member_id'],
+                'order_name' => date('Y-m-d H:i:s') . '-订单',
+                'order_amount_total' => $params['order_amount_total'],
+                'order_amount_pay' => $params['order_status_payment'] == 'SUCCESS' ? $params['order_amount_pay'] : 0,
+                'order_amount_paid' => $params['order_status_payment'] == 'SUCCESS' ? $params['order_amount_pay'] : 0,
+                'order_category' => $orderCategory,
+                'order_classify' => $orderCategory,
+                'order_is_complete' => floatval($params['order_amount_pay']) >= floatval($params['order_amount_total']) && $params['order_status_payment'] == 'SUCCESS' ? 'Y' : 'N',
+                'order_status_system' => floatval($params['order_amount_pay']) >= floatval($params['order_amount_total']) && $params['order_status_payment'] == 'SUCCESS' ? 'DONE' : 'PAYING',
+                'order_status_payment' => floatval($params['order_amount_pay']) >= floatval($params['order_amount_total']) && $params['order_status_payment'] == 'SUCCESS' ? 'SUCCESS' : 'PENDING',
+                'order_status_storage' => $params['order_status_storage'],
+                'order_platform' => $params['order_platform'],
+                'order_remark' => $params['order_remark'] ?? '',
+                'order_discount_json' => $params['order_discount_json'] ?? '[]',
+                'order_config_json' => json_encode(['order_category' => 'RECHARGE']),
+                'order_express_json' => $params['order_express_json'] ?? '[]',
+                'order_extend_json' => $params['order_extend_json'] ? json_encode($params['order_extend_json']) : '[]',
+                'order_addtimes' => time()
+            ];
+
+            Order::insert($data);
+        } catch (\Exception $e) {
+            dump($e->getMessage());
+            throw new BusinessException('订单创建信息失败');
+        }
+    }
+
+    /**
+     * @Desc
+     * @Author Gorden
+     * @Date 2024/6/7 10:25
+     *
+     * @param $params
+     * @return void
+     * @throws BusinessException
+     */
+    public function insertSheet($params)
+    {
+        try {
+            $orderSheetIds = [];
+            foreach ($params['goodsContentList'] as $goods) {
+                //{"unit": "份", "table": null, "premises": "15"}
+                $price = floatval($goods['goods_sales_price']);
+                $extendJson['unit'] = $goods['sku_name'];
+                if (isset($params['submit_premises_id'])) {
+                    $extendJson['premises'] = $params['submit_premises_id'];
+                }
+                if (isset($params['submit_goods_classify']) && $params['submit_goods_classify'] == 'MEALS') {
+                    $extendJson['table'] = null;
+                }
+                $orderSheetStatus = 'PAYING';
+                if ($params['settlement_now'] == 'Y' && $params['order_status_payment'] == 'SUCCESS') {
+                    if (floatval($params['order_amount_pay']) >= floatval($params['order_amount_total'])) {
+                        $orderSheetStatus = 'DONE';
+                    } else {
+                        $orderSheetStatus = 'BEING';
+                    }
+                }
+                $data = [
+                    'join_sheet_member_id' => $params['join_order_member_id'],
+                    'join_sheet_order_id' => $params['orderId'],
+                    'join_sheet_goods_id' => $goods['goods_id'],
+                    'join_sheet_goods_sku_id' => $goods['sku_id'],
+                    'order_sheet_status' => $orderSheetStatus,
+                    'order_sheet_category' => 'RECHARGE',
+                    'order_sheet_num' => $goods['nbr'],
+                    'order_sheet_price' => $goods['goods_sales_price'],
+                    'order_sheet_amount' => $price * $goods['nbr'],
+                    'order_sheet_pay' => $price * $goods['nbr'],
+                    'order_sheet_task_status' => 'NONE',
+                    'order_sheet_remark' => $params['order_remark'] ?? '',
+                    'order_sheet_addtimes' => time(),
+                    'order_sheet_extend_json' => json_encode($extendJson)
+                ];
+
+                $orderSheetId = OrderSheet::insertGetId($data);
+                $orderSheetIds[] = $orderSheetId;
+
+                // 减库存,规格和总库存
+                if (!isset($params['submit_goods_classify']) || !in_array($params['submit_goods_classify'], ['MEALS', 'PACKAGE'])) {
+                    $goodsSku = GoodsSku::where('goods_sku_id', $goods['sku_id'])->first();
+                    $skuStorageJson = json_decode($goodsSku->goods_sku_storage_json, true);
+                    if (isset($skuStorageJson['storage']) && !empty($skuStorageJson['storage'])) {
+                        $skuStorageJson['storage'] = $skuStorageJson['storage'] - $goods['nbr'];
+                    }
+
+                    if (!isset($skuStorageJson['storage']) || (!empty($skuStorageJson['storage']) && $skuStorageJson['storage'] < 0)) {
+                        throw new BusinessException('库存不足');
+                    }
+                    $goodsSku->goods_sku_storage_json = json_encode($skuStorageJson);
+                    $goodsSku->save();
+                }
+
+
+                $goodsRunning = GoodsRunning::where('join_running_goods_id', $goods['goods_id'])->first();
+                $goodsRunning->goods_running_storage = $goodsRunning->goods_running_storage - $goods['nbr'];
+                if ($goodsRunning->goods_running_storage < 0) {
+                    throw new BusinessException('库存不足');
+                }
+                $goodsRunning->goods_running_sale = $goodsRunning->goods_running_sale + $goods['nbr'];
+                $goodsRunning->save();
+            }
+            return $orderSheetIds;
+        } catch (\support\exception\BusinessException $e) {
+            dump($e->getMessage() . '||' . $e->getLine());
+            throw new BusinessException($e->getMessage());
+        } catch (\Exception $e) {
+            dump($e->getMessage() . '||' . $e->getLine());
+            throw new BusinessException('订单创建失败');
+        }
+    }
+
+    /**
+     * @Desc
+     * @Author Gorden
+     * @Date 2024/6/7 10:35
+     *
+     * @param $params
+     * @return void
+     * @throws BusinessException
+     */
+    public function insertPayDetail($params)
+    {
+        try {
+            if (in_array($params['pay_category'], ['WXPAY', 'ALIPAY'])) {
+                $payPrepayid = $params['pay_category'];
+            } else if ($params['pay_category'] == 'OFFLINE') {
+                $payPrepayid = 'OFFLINE';
+            } else if ($params['pay_category'] == 'OFFLINE_ALIPAY') {
+                $payPrepayid = 'OFFLINE_ALIPAY';
+            } else if ($params['pay_category'] == 'OFFLINE_WXPAY') {
+                $payPrepayid = 'OFFLINE_WXPAY';
+            } else if ($params['pay_category'] == 'MONEY') {
+                $payPrepayid = 'MONEY';
+            } else {
+                $payPrepayid = $params['join_order_member_id'] . '-' . $params['pay_category'];
+            }
+
+            $sheet = OrderSheet::with('goods')->where('join_sheet_order_id', $params['orderId'])->first();
+            $payExtendJson = [];
+            if (!empty($sheet->goods)) {
+                $goodsAttributeJson = json_decode($sheet->goods->goods_attribute_json, true);
+                $addedRate = 0;
+                if (!empty($goodsAttributeJson['added'])) {
+                    $addedRate = $goodsAttributeJson['added']['nbr'];
+                }
+                $payExtendJson = [
+                    'added_rate' => $addedRate,
+                    'added_amount' => $addedRate * $params['order_amount_pay']
+                ];
+            }
+
+            $data = [
+                'join_pay_member_id' => $params['join_order_member_id'],
+                'join_pay_order_id' => $params['orderGroupId'],
+                'pay_status' => $params['order_status_payment'] == 'SUCCESS' ? 'SUCCESS' : 'WAITING',
+                'pay_category' => $params['goods_classify'],
+                'pay_amount' => $params['order_amount_pay'],
+                'pay_prepayid' => $payPrepayid,
+                'pay_paytimes' => date('Y-m-d H:i:s'),
+                'join_pay_object_json' => !empty($params['orderId']) ? json_encode(['order_id' => $params['orderId']]) : '[]',
+                'pay_json_request' => json_encode($params),
+                'pay_json_response' => $params['pay_json_response'] ?? '[]',
+                'pay_extend_json' => json_encode($payExtendJson),
+                'pay_remark' => $params['order_remark'] ?? '',
+                'pay_addtimes' => time(),
+            ];
+
+            $payId = PayDetail::insertGetId($data);
+
+            return $payId;
+        } catch (\Exception $e) {
+            dump($e->getMessage());
+            throw new BusinessException('创建支付记录失败');
+        }
+    }
+
+
+    /**
+     * @Desc 订单商品详情
+     * @Author Gorden
+     * @Date 2024/3/29 8:50
+     *
+     * @param Request $request
+     * @return Response
+     */
+    public function sheet(Request $request)
+    {
+        try {
+            $orderId = $request->get('order_id');
+            $orderSheet = OrderSheet::with([
+                'member' => function ($query) {
+                    $query->select('member_id', 'member_mobile', 'member_is_owner', 'join_member_role_id', 'member_is_vip', 'member_is_partner', 'member_is_referrer');
+                },
+                'goods' => function ($query) {
+                    $query->select('goods_id', 'goods_name', 'goods_cover', 'goods_market_price', 'goods_sales_price', 'goods_classify', 'goods_if_express');
+                },
+                'memberInfo',
+                'cert',
+                'sku' => function ($query) {
+                    $query->where('goods_sku_status', 'ON')
+                        ->select('goods_sku_id', 'join_sku_goods_id', 'goods_sku_specs_json', 'goods_sku_sales_price');
+                },
+                'skus',
+                'refund' => function ($query) {
+                    $query->select('join_return_order_id', 'order_return_status');
+                }
+            ])->where('join_sheet_order_id', $orderId)
+                ->orderBy('order_sheet_id', 'DESC')
+                ->get()
+                ->toArray();
+
+            $order = Order::where('order_id', $orderId)->first();
+            $express = OrderExpress::where('join_express_order_id', $orderId)->first();
+            $premises = '';
+            if ($express && $express->order_express_type == '自提') {
+                $premises = $express->order_express_company;
+            }
+            $sheetAmount = 0;
+            foreach ($orderSheet as &$item) {
+                $sheetAmount += $item['order_sheet_amount'];
+                $item['goods']['goods_cover'] = getenv('STORAGE_DOMAIN') . $item['goods']['goods_cover'];
+                if (!empty($item['goods']) && $item['goods']['goods_classify'] == 'PACKAGE') {
+                    $components = GoodsComponent::with('goods')
+                        ->where('join_component_master_goods_id', $item['goods']['goods_id'])
+                        ->select('join_component_master_goods_id', 'join_component_goods_id', 'goods_component_price',
+                            'goods_component_price', 'goods_component_json')
+                        ->get()
+                        ->toArray();
+                    $goodsArr = [];
+                    foreach ($components as $component) {
+                        $configJson = !empty($component['goods_component_json']) ? json_decode($component['goods_component_json'], true) : [];
+                        if (!empty($component['goods'])) {
+                            $supplierName = Supplier::where('supplier_id', $component['goods']['join_goods_supplier_id'])->value('supplier_name');
+                            $benefit = MemberBenefit::where('join_benefit_member_id', $item['join_sheet_member_id'])
+                                ->where('join_benefit_goods_id', $component['goods']['goods_id'])
+                                ->where('join_benefit_order_id', $orderId)
+                                ->first();
+                            $goodsArr[] = [
+                                'goods_name' => $component['goods']['goods_name'],
+                                'goods_cover' => getenv('STORAGE_DOMAIN') . $component['goods']['goods_cover'],
+                                'supplier_name' => $supplierName,
+                                'nbr' => $configJson['nbr'] ?? 0,
+                                'used' => !empty($benefit->member_benefit_used_count) ? intval($benefit->member_benefit_used_count) : ''
+                            ];
+                        }
+                    }
+
+                    $item['goods']['components'] = $goodsArr;
+                }
+                if (!empty($item['sku'])) {
+                    if (!empty($item['sku']['goods_sku_specs_json'])) {
+                        $specsJson = json_decode($item['sku']['goods_sku_specs_json'], true);
+                        $skuName = '';
+                        foreach ($specsJson as $specsKey => $skuSpecs) {
+                            if (is_array($skuSpecs)) {
+                                $skuName = $skuName . ' ' . implode(' ', $skuSpecs) . ';';
+                            } else {
+                                $skuName = $skuName . ' ' . $skuSpecs . ';';
+                            }
+                        }
+                        $item['sku']['goods_sku_title'] = rtrim($skuName, ';');
+                    }
+                }
+                if (!empty($item['skus'])) {
+                    foreach ($item['skus'] as $key => $skus) {
+                        if (!empty($skus['goods_sku_specs_json'])) {
+                            $item['skus'][$key]['goods_sku_specs_json'] = json_decode($skus['goods_sku_specs_json']);
+
+                            $skuName = '';
+                            foreach ($item['skus'][$key]['goods_sku_specs_json'] as $specsKey => $skuSpecs) {
+                                $keyStr = ($specsKey == '规格') ? '' : ($specsKey . ':');
+                                if (is_array($skuSpecs)) {
+                                    $skuName = $skuName . $keyStr . ' ' . implode(' ', $skuSpecs) . '; ';
+                                } else {
+                                    $skuName = $skuName . $keyStr . ' ' . $skuSpecs . '; ';
+                                }
+                            }
+                            $item['skus'][$key]['sku_name'] = rtrim($skuName, '; ');
+                        }
+                    }
+                } else {
+                    $item['skus'] = [];
+                }
+                if (in_array($item['goods']['goods_classify'], ['SERVICE', 'CHNMED', 'CHNNCD', 'PACKAGE']) && $order->order_status_system == 'DONE') {
+                    $item['appontment'] = [];
+                    $appontments = Appointment::where('join_appointment_order_id', $orderId)
+                        ->where('appointment_status', 'DONE')
+                        ->select('appointment_status', 'appointment_id', 'appointment_done_datetime', 'appointment_done_json', 'appointment_apply_json')
+                        ->get()
+                        ->toArray();
+                    foreach ($appontments as $appontment) {
+                        $doneJson = [];
+                        $username = '';
+                        if (!empty($appontment['appointment_done_json'])) {
+                            $doneJson = json_decode($appontment['appointment_done_json'], true);
+                            if (isset($doneJson['charge'])) {
+                                $username = SysUser::where('user_id', $doneJson['charge']['charge_user_id'])->value('user_name');
+                            }
+                        }
+                        $person = 1;
+                        if (!empty($appontment->appointment_apply_json)) {
+                            $applyJson = json_decode($appontment->appointment_apply_json, true);
+                            if (isset($applyJson['person'])) {
+                                $person = $applyJson['person'];
+                            }
+                        }
+                        $item['appontment'][] = [
+                            'member' => ($item['cert'] ? $item['cert']['member_cert_name'] . '-' : '') . ($item['member'] ? $item['member']['member_mobile'] : ''),
+                            'goods_name' => $item['goods']['goods_name'],
+                            'premisses' => isset($doneJson['charge']) ? $doneJson['charge']['charge_premises'] : '',
+                            'username' => $username,
+                            'nbr' => $person,
+                            'done_time' => $appontment['appointment_done_datetime'],
+                            'appointment_status' => $appontment['appointment_status'],
+                        ];
+                    }
+                }
+                if (!empty($item['order_sheet_extend_json']) && !$express) {
+                    $extendJson = json_decode($item['order_sheet_extend_json'], true);
+                    if (isset($extendJson['address_id'])) {
+                        $address = ClientConfig::where('client_config_id', $extendJson['address_id'])->first();
+                        if (!empty($address)) {
+                            $valJson = json_decode($address->client_config_val_json, true);
+                            $express = [
+                                'order_express_address' => $valJson['address'] . ($valJson['numbers'] ?? ''),
+                                'order_express_city' => $valJson['city'],
+                                'order_express_mobile' => $valJson['mobile'],
+                                'order_express_person' => $valJson['person']
+                            ];
+                        }
+                    }
+                }
+                $item['member']['level'] = '普通会员';
+                if (!empty($item['member']['join_member_role_id'])) {
+                    $item['member']['level'] = MemberRole::where('member_role_id', $item['member']['join_member_role_id'])->value('member_role_name');
+                }
+
+                if (!empty($item['member_info'])) {
+                    if (empty($item['member_info']['member_info_headimg']) || substr($item['member_info']['member_info_headimg'], 0, 1) == '.') {
+                        $item['member_info']['member_info_headimg'] = "https://img.wanyuewellness.com.cn/images/avatar_default.png";
+                    }
+                }
+            }
+            $order->sheet_amount = number_format($sheetAmount, 2);
+            $payDetails = PayDetail::where('join_pay_order_id', $order->order_groupby)
+                ->whereJsonContains('join_pay_object_json->order_id', $orderId)
+                ->where('pay_category', '<>', 'REFUND')
+                ->where('pay_status', 'SUCCESS')
+                ->select('pay_id', 'pay_category', 'pay_prepayid', 'pay_paytimes', 'pay_status', 'pay_amount', 'pay_extend_json')
+                ->get();
+            if (count($payDetails) > 1) {
+                $order->pay_category = 'CONSTITUTE';
+            }
+            $payDetail = !empty($payDetails) && count($payDetails) > 0 ? $payDetails[0] : [];
+            if (!empty($payDetail) && !empty($payDetail->pay_extend_json)) {
+                $payExtendJson = json_decode($payDetail->pay_extend_json, true);
+                $order->cancel_times = $payExtendJson['cancel_times'] ?? '';
+//            $payDetail->cancel_times = $payExtendJson['cancel_times'] ?? '';
+            }
+            if (!empty($payDetail) && !empty($payDetail->pay_prepayid)) {
+                $categoryArray = explode('-', $payDetail->pay_prepayid);
+                if (isset($categoryArray[1])) {
+                    $payDetail->pay_category = $categoryArray[1];
+                } else if (in_array($categoryArray[0], ['WXPAY', 'ALIPAY', 'OFFLINE', 'OFFLINE_ALIPAY', 'OFFLINE_WXPAY', 'MONEY'])) {
+                    $payDetail->pay_category = $categoryArray[0];
+                }
+            }
+            $refund = OrderReturn::where('join_return_order_id', $orderId)
+                ->select('order_return_status', 'order_return_apply_datetime', 'order_return_apply_json', 'order_return_accept_datetime', 'order_return_refund_json', 'order_return_extend_json')
+                ->first();
+            if (!empty($refund->order_return_refund_json)) {
+                $returnRefundJson = json_decode($refund->order_return_refund_json, true);
+                if (isset($returnRefundJson['user_id'])) {
+                    $userName = SysUser::where('user_id', $returnRefundJson['user_id'])->value('user_name');
+                    $returnRefundJson['person'] = $userName;
+                    unset($returnRefundJson['user_id']);
+                }
+
+                $refund->order_return_refund_json = json_encode($returnRefundJson);
+            }
+            if (!empty($order->order_config_json)) {
+                $orderConfigJson = json_decode($order->order_config_json, true);
+                if (isset($orderConfigJson['reach'])) {
+                    $order->reach = $orderConfigJson['reach'];
+                }
+                if (isset($orderConfigJson['table'])) {
+                    $order->table = $orderConfigJson['table'];
+                }
+                if (isset($orderConfigJson['eat'])) {
+                    $order->eat = $orderConfigJson['eat'];
+                }
+                if (isset($orderConfigJson['express'])) {
+                    $order->express = $orderConfigJson['express'];
+                }
+                if (isset($orderConfigJson['premises'])) {
+                    $order->premises = $orderConfigJson['premises'];
+                }
+                if (isset($orderConfigJson['tableid'])) {
+                    $order->dept_table_id = $orderConfigJson['tableid'];
+                }
+            }
+            if (!empty($order->order_extend_json)) {
+                $orderExtendJson = json_decode($order->order_extend_json, true);
+                $order->referee = $orderExtendJson['referee'] ?? '';
+                if (isset($orderExtendJson['cancel_times'])) {
+                    $order->cancel_times = $orderExtendJson['cancel_times'];
+                }
+                if (isset($orderExtendJson['free_remark'])) {
+                    $order->free_remark = $orderExtendJson['free_remark'];
+                }
+                if (isset($orderExtendJson['dept_id'])) {
+                    $order->dept_id = $orderExtendJson['dept_id'];
+                }
+            }
+            $discount = ['coupon_name' => '', 'classify' => '', 'value' => 0];
+            if (!empty($order->order_discount_json)) {
+                $orderDiscountJson = json_decode($order->order_discount_json, true);
+                foreach ($orderDiscountJson as $discountItem) {
+                    if (!empty($discountItem['coupon_id'])) {
+                        $coupon = Coupon::where('coupon_id', $discountItem['coupon_id'])
+                            ->select('coupon_name', 'coupon_classify', 'coupon_category', 'coupon_value', 'coupon_minimum_limit')
+                            ->first();
+                        if (!$coupon) {
+                            continue;
+                        }
+                        $classify = CouponService::couponClassifyInfo($coupon->coupon_classify, $coupon->coupon_category, $coupon->coupon_value, $coupon->coupon_minimum_limit);
+                        $discount['coupon_name'] .= $coupon->coupon_classify . ':' . $coupon->coupon_name . '(优惠¥' . sprintf("%.2f", $discountItem['coupon_value']) . '), ';
+                    }
+                    if ($discountItem['coupon_classify'] == '退款') {
+                        continue;
+                    }
+                    if (empty($discountItem['coupon_id']) && !empty($discountItem['coupon_classify'])) {
+                        if (!empty($discountItem['coupon_detail_id'])) {
+
+                            $discount['classify'] .= $discountItem['coupon_detail_id'][0] . '(优惠¥' . sprintf("%.2f", $discountItem['coupon_value']) . '), ';
+                        } else {
+                            $discount['classify'] .= $discountItem['coupon_classify'] . '(优惠¥' . sprintf("%.2f", $discountItem['coupon_value']) . '), ';
+                        }
+                    }
+                    if (!empty($discountItem['coupon_value'])) {
+                        $discount['value'] += $discountItem['coupon_value'];
+                    }
+                }
+                if (!empty($discount['coupon_name'])) {
+                    $discount['coupon_name'] = rtrim($discount['coupon_name'], ', ');
+                }
+                if (!empty($discount['classify'])) {
+                    $discount['classify'] = rtrim($discount['classify'], ', ');
+                }
+            }
+            $discount['value'] = sprintf("%.2f", $discount['value']);
+            $order->discount = $discount;
+
+            $order->premises = $order->premises ?? $premises;
+            $data = [
+                'order' => $order,
+                'refund' => json_decode(json_encode($refund)),
+                'sheet' => json_decode(json_encode($orderSheet)),
+                'express' => json_decode(json_encode($express)),
+                'payDetail' => json_decode(json_encode($payDetail)),
+                'payDetails' => json_decode(json_encode($payDetails))
+            ];
+
+            return json_success('', $data);
+
+        } catch (\Exception $e) {
+            dump($e->getMessage());
+        }
+    }
+
+    /**
+     * @Desc 获取分期的订单
+     * @Author Gorden
+     * @Date 2024/9/10 15:14
+     *
+     * @param Request $request
+     * @return Response
+     */
+    public function getPaidOrder(Request $request)
+    {
+        $memberId = $request->get('member_id');
+        if (!$memberId) {
+            return json_fail('参数异常');
+        }
+
+        $order = Order::where('join_order_member_id', $memberId)
+            ->where('order_category', 'RECHARGE')
+            ->where('order_status_system', 'PAYING')
+            ->select('order_id', 'order_amount_total', 'order_amount_paid', 'order_amount_pay', 'order_extend_json')
+            ->first();
+
+        return json_success('', $order);
+    }
+
+    /**
+     * @Desc 上传支付凭证
+     * @Author Gorden
+     * @Date 2024/9/12 10:14
+     *
+     * @param Request $request
+     * @return Response
+     */
+    public function uploadTicket(Request $request)
+    {
+        $payId = $request->post('pay_id');
+        $url = $request->post('url');
+        if (!$payId || !$url) {
+            return json_fail("参数异常");
+        }
+        $url = str_replace(getenv("STORAGE_DOMAIN"), '', $url);
+        try {
+            $payDetail = PayDetail::where('pay_id', $payId)->first();
+            if (!$payDetail) {
+                return json_fail('数据异常');
+            }
+            $extendJson = [];
+            if (!empty($payDetail->pay_extend_json)) {
+                $extendJson = json_decode($payDetail->pay_extend_json, true);
+            }
+            $extendJson['ticket'] = $url;
+
+            $payDetail->pay_extend_json = json_encode($extendJson);
+            dump($payDetail->save());
+
+            return json_success('success');
+        } catch (\Exception $e) {
+            return json_fail("上传附件失败");
+        }
+    }
+
+
+    /**
+     * @Desc 查询订单状态
+     * @Author Gorden
+     * @Date 2024/8/19 11:55
+     *
+     * @param Request $request
+     * @return Response|void
+     */
+    public function getOrderPayStatus(Request $request)
+    {
+        $groupId = $request->get('group_id');
+        if (!$groupId) {
+            return json_fail('参数异常');
+        }
+
+        $order = Order::where('order_groupby', $groupId)->first();
+        if (empty($order)) {
+            return json_fail('订单不存在');
+        }
+        $order = $order->toArray();
+        $sheet = OrderSheet::where('join_sheet_order_id', $order['order_id'])
+            ->select('order_sheet_id', 'join_sheet_goods_id', 'join_sheet_goods_sku_id')
+            ->first();
+        $payDetailType = PayDetail::where('join_pay_order_id', $groupId)->pluck('pay_prepayid')->toArray();
+        try {
+            Db::beginTransaction();
+            $payStatus = 'N';
+            $payAmount = 0;
+            if (in_array('WXPAY', $payDetailType)) {
+//                $result = Pay::wechat(config('payment.wxpay'))->find($groupId, 'pos');
+//                $result = json_decode(json_encode($result), true);
+                $result = '{"return_code":"SUCCESS","return_msg":"OK","result_code":"SUCCESS","mch_id":"1680393367","appid":"wxc6274da7198e3eb4","openid":"o3JAn6Ii_bAlxS-jbNEC4WnPhdwM","is_subscribe":"N","trade_type":"MICROPAY","trade_state":"SUCCESS","bank_type":"OTHERS","total_fee":"50","fee_type":"CNY","cash_fee":"1000","cash_fee_type":"CNY","transaction_id":"4200067718202409250802875650","out_trade_no":"OD24092518408RV7","attach":[],"time_end":"20240925184009","trade_state_desc":"支付成功","nonce_str":"OeGOkjch4eaV5qIt","sign":"6DCB3BFC594EBC018A2BEE2C3DFEA4E3"}';
+                $result = json_decode($result, true);
+                if (!empty($result['return_code']) && $result['return_code'] == 'SUCCESS' && !empty($result['result_code']) && $result['result_code'] == 'SUCCESS' && !empty($result['trade_state']) && $result['trade_state'] == 'SUCCESS') {
+                    $payStatus = 'Y';
+                    $orderUpdateData['order_status_payment'] = 'SUCCESS';
+                    $orderUpdateData['order_status_system'] = 'DONE';
+                    $orderUpdateData['order_is_complete'] = 'Y';
+
+                    // 主订单
+                    Order::where('order_groupby', $groupId)->update($orderUpdateData);
+                    // Sheet
+                    OrderSheet::where('join_sheet_order_id', $order['order_id'])->where('order_sheet_status', 'PAYING')->update(['order_sheet_status' => 'DONE']);
+                    // 支付记录
+                    $payDetail = PayDetail::where('join_pay_order_id', $order['order_groupby'])->where('pay_prepayid', 'WXPAY')->first();
+                    $payDetail->pay_status = 'SUCCESS';
+                    $payDetail->pay_paytimes = date('Y-m-d H:i:s');
+                    $payDetail->pay_json_response = json_encode($result);
+                    $payDetail->save();
+                }
+            } else if (in_array('ALIPAY', $payDetailType)) {
+                $result = Pay::alipay(config('payment.alipay'))->find($groupId);
+                $result = json_decode(json_encode($result), true);
+//                $result = '{"code":"10000","msg":"Success","buyer_logon_id":"138******93","buyer_pay_amount":"5.87","fund_bill_list":[{"amount":"5.69","fund_channel":"ALIPAYACCOUNT"},{"amount":"0.18","fund_channel":"COUPON"},{"amount":"0.13","fund_channel":"DISCOUNT"}],"invoice_amount":"5.69","out_trade_no":"OD2409251550Q07A","point_amount":"0.00","receipt_amount":"0.01","send_pay_date":"2024-09-25 15:50:22","total_amount":"0.01","trade_no":"2024092523001439431419750998","trade_status":"TRADE_SUCCESS","buyer_open_id":"04309N2aVhSZz4cKwN_DN2DQa7ekM3z5n8kscQHsmIZOJsf"}';
+//                $result = json_decode($result, true);
+                if (!empty($result['code']) && $result['code'] == '10000' && !empty($result['trade_status']) && $result['trade_status'] == 'TRADE_SUCCESS') {
+                    $payStatus = 'Y';
+                    $orderUpdateData['order_status_payment'] = 'SUCCESS';
+                    $orderUpdateData['order_status_system'] = 'DONE';
+                    $orderUpdateData['order_is_complete'] = 'Y';
+
+                    // 主订单
+                    Order::where('order_groupby', $groupId)->update($orderUpdateData);
+                    // Sheet
+                    OrderSheet::where('join_sheet_order_id', $order['order_id'])->where('order_sheet_status', 'PAYING')->update(['order_sheet_status' => 'DONE']);
+                    // 支付记录
+                    $payDetail = PayDetail::where('join_pay_order_id', $order['order_groupby'])->where('pay_prepayid', 'WXPAY')->first();
+                    $payDetail->pay_status = 'SUCCESS';
+                    $payDetail->pay_paytimes = date('Y-m-d H:i:s');
+                    $payDetail->pay_json_response = json_encode($result);
+                    $payDetail->save();
+                }
+            }
+            if ($payStatus == 'Y') {
+
+                Db::commit();
+
+                $params['member_id'] = $order['join_order_member_id'];
+                $params['orderId'] = $order['order_id'];
+                $params['order_amount_pay'] = $payAmount;
+                $params['order_amount_total'] = $order['order_amount_total'];
+                $params['join_sheet_goods_id'] = $sheet->join_sheet_goods_id;
+                if (!empty($order['order_extend_json'])) {
+                    $orderExtendJson = json_decode($order['order_extend_json'], true);
+                    $params['dept_id'] = $orderExtendJson['dept_id'] ?? '';
+                    $params['dept_name'] = $orderExtendJson['dept_name'] ?? '';
+                }
+                // 入收支明细表
+                $params['orderId'] = $order['order_id'];
+                $params['inout_category'] = '会员充值订单收入';
+                Event::dispatch('statistics.inout.in', $params);
+
+                // 充值回调
+                (new \app\admin\controller\notify\RechargeController)->disposePaySuccess($payDetail->pay_id);
+
+                return json_success('success');
+            }
+
+            Db::rollBack();
+            return json_fail('没有查询到记录');
+        } catch (BusinessException $e) {
+            Db::rollBack();
+            _syslog("支付轮询", '订单支付异常:' . $e->getMessage());
+            return json_fail($e->getMessage());
+        } catch (\Exception $e) {
+            dump($e->getMessage());
+            Db::rollBack();
+            return json_fail('查询失败');
+        }
+    }
+}

+ 3 - 0
app/admin/service/goods/GoodsService.php

@@ -201,6 +201,9 @@ class GoodsService
             ->when($classify != '', function ($query) use ($classify, $categoryId) {
                 if ($classify == 'GOODS' && empty($categoryId)) {
                     $query->whereIn('join_goods_category_id', ['6', '7', '8', '9', '10', '11', '12', '30']);
+                } else if ($classify == 'RECHARGE' && empty($categoryId)) {
+                    $query->where('goods_status','ON');
+                    $query->where('goods_classify', $classify);
                 } else if ($classify != 'GOODS' && empty($categoryId)) {
                     $query->where('goods_classify', $classify);
                 }

+ 2099 - 0
app/admin/service/goods/MemberRechargeBenefitService.php

@@ -0,0 +1,2099 @@
+<?php
+
+namespace app\admin\service\goods;
+
+use app\common\Tree;
+use app\model\Appointment;
+use app\model\Coupon;
+use app\model\Goods;
+use app\model\GoodsComponent;
+use app\model\GoodsDetail;
+use app\model\GoodsLabel;
+use app\model\GoodsRunning;
+use app\model\GoodsSku;
+use app\model\OrderSheet;
+use app\model\Supplier;
+use app\model\SysCategory;
+use app\model\SysDept;
+use app\model\SysUser;
+use support\Db;
+use support\exception\BusinessException;
+use support\Redis;
+use support\Request;
+use support\Response;
+use Tinywan\Jwt\JwtToken;
+
+class MemberRechargeBenefitService
+{
+    public static function select(Request $request, $classify = "GOODS")
+    {
+        $page = $request->get('page', 1);
+        $pageSize = $request->get('pageSize', 20);
+        $goodsName = $request->get('goods_name', '');
+        $categoryId = $request->get('join_goods_category_id', null);
+        $goodsCategory = $request->get('goods_category', null);
+        $goodsSupplierId = $request->get('join_goods_supplier_id', null);
+        $goodsStatus = $request->get('goods_status', null);
+        $type = $request->get('type', '');
+        if ($categoryId != null) {
+            $categoryPath = SysCategory::where('category_id', $categoryId)->value('category_super_path');
+            $categoryPath .= '#' . $categoryId . '#';
+            $categoryIds = SysCategory::where('category_super_path', 'like', $categoryPath . '%')->pluck('category_id')->toArray();
+            $categoryIds[] = intval($categoryId);
+            if (!empty($categoryIds)) {
+                $categoryId = $categoryIds;
+            } else {
+                $categoryId = [intval($categoryId)];
+            }
+        }
+
+        $rows = Goods::with([
+            'category' => function ($query) {
+                $query->select('category_id', 'category_name');
+            },
+            'running' => function ($query) {
+                $query->select('join_running_goods_id', 'goods_running_storage');
+            },
+            'supplier' => function ($query) {
+                $query->select('supplier_id', 'supplier_name');
+            },
+            'user' => function ($query) {
+                $query->select('user_id', 'user_name');
+            },
+            'updateUser' => function ($query) {
+                $query->select('user_id', 'user_name');
+            },
+        ])->leftJoin('goods_running', 'goods_running.join_running_goods_id', '=', 'goods.goods_id')
+            ->select('goods_id', 'join_goods_category_id', 'join_goods_supplier_id', 'creator_user_id', 'updator_user_id', 'goods_status', 'goods_sales_price', 'goods_category', 'goods_name', 'goods_title', 'goods_cover', 'goods_sort', 'goods_attribute_json', 'goods_addtimes', 'goods_updatetimes')
+            ->when($goodsName != '', function ($query) use ($goodsName) {
+                $query->where(function ($q) use ($goodsName) {
+                    $q->where('goods_name', 'like', '%' . $goodsName . '%');
+//                        ->OrWhere('goods_title', 'like', '%' . $goodsName . '%');
+                });
+            })->when($categoryId != null, function ($query) use ($categoryId) {
+                $query->whereIn('join_goods_category_id', $categoryId);
+            })->when($goodsCategory != null, function ($query) use ($goodsCategory) {
+                dump($goodsCategory);
+                $query->where('goods_category', $goodsCategory);
+            })
+            ->when($classify != '', function ($query) use ($classify) {
+                dump($classify);
+                $query->where('goods_classify', $classify);
+            })->when(!empty($goodsSupplierId), function ($query) use ($goodsSupplierId) {
+                $query->where('join_goods_supplier_id', $goodsSupplierId);
+            })->when(!empty($goodsStatus), function ($query) use ($goodsStatus) {
+                $query->where('goods_status', $goodsStatus);
+            })
+            ->where('goods_status', 'ON')
+            ->orderBy('goods_sort', 'DESC')
+            ->orderBy('goods_addtimes', 'DESC')
+            ->forPage($page, $pageSize)
+            ->get()
+            ->toArray();
+
+        $total = Goods::leftJoin('goods_running', 'goods_running.join_running_goods_id', '=', 'goods.goods_id')
+            ->when($goodsName != '', function ($query) use ($goodsName) {
+                $query->where(function ($q) use ($goodsName) {
+                    $q->where('goods_name', 'like', '%' . $goodsName . '%');
+//                        ->OrWhere('goods_title', 'like', '%' . $goodsName . '%');
+                });
+            })->when($categoryId != null, function ($query) use ($categoryId) {
+                $query->whereIn('join_goods_category_id', $categoryId);
+            })->when($goodsCategory != null, function ($query) use ($goodsCategory) {
+                $query->where('goods_category', $goodsCategory);
+            })->when($classify != '', function ($query) use ($classify) {
+                $query->where('goods_classify', $classify);
+            })->when(!empty($goodsSupplierId), function ($query) use ($goodsSupplierId) {
+                $query->where('join_goods_supplier_id', $goodsSupplierId);
+            })->when(!empty($goodsStatus), function ($query) use ($goodsStatus) {
+                $query->where('goods_status', $goodsStatus);
+            })
+            ->where('goods_status', 'ON')
+            ->count();
+
+        foreach ($rows as &$row) {
+            $row['goods_cover'] = getenv('STORAGE_DOMAIN') . $row['goods_cover'];
+            if (isset($row['running'])) {
+                $row['running']['goods_running_storage'] = intval($row['running']['goods_running_storage']);
+            }
+            if (!empty($row['goods_attribute_json'])) {
+                $row['goods_attribute_json'] = json_decode($row['goods_attribute_json']);
+            }
+            if (!empty($row['goods_category']) && $row['goods_category'] == 'INDEX') {
+                $row['goods_recommend_index'] = 'INDEX';
+            }
+        }
+
+        return json_success('', compact('rows', 'page', 'pageSize', 'total'));
+    }
+
+    public static function selectAll($goodsIds)
+    {
+        $goods = Goods::where('goods_status', 'ON')
+            ->when($goodsIds != '', function ($query) use ($goodsIds) {
+                $query->whereIn('goods_id', $goodsIds);
+            })
+            ->select('goods_id', 'goods_name')
+            ->get();
+
+        return json_success('', $goods);
+    }
+
+    public static function selectAllByGoodsName($goodsName)
+    {
+        $goods = Goods::with('sku')
+            ->where('goods_status', 'ON')
+            ->when($goodsName != '', function ($query) use ($goodsName) {
+                $query->where('goods_name', 'like', "%" . $goodsName . '%');
+            })
+            ->select('goods_id', 'goods_name', 'goods_classify')
+            ->get()
+            ->toArray();
+        foreach ($goods as &$item) {
+            if (!empty($item['sku'])) {
+                foreach ($item['sku'] as $key => $sku) {
+                    $specsJson = json_decode($sku['goods_sku_specs_json'], true);
+                    $skuTitle = '';
+                    foreach ($specsJson as $item2) {
+                        if (is_array($item2)) {
+                            $item2 = implode(',', $item2);
+                        }
+                        $skuTitle .= $item2 . '-';
+                    }
+                    $item['sku'][$key]['goods_sku_id'] = strval($item['sku'][$key]['goods_sku_id']);
+                    $item['sku'][$key]['goods_sku_title'] = rtrim($skuTitle, '-');
+                }
+            }
+        }
+
+        return json_success('', $goods);
+    }
+
+    public static function selectAllByCategoryForRuleAddComponent($category = "GOODS")
+    {
+        $categoryIds = [];
+        $categorySuperIds = [];
+        if ($category == 'GOODS') {
+            $categorySuperIds = [5];
+        } elseif ($category == 'SERVICE') {
+            $categorySuperIds = [31, 154, 42, 65, 30, 66, 72, 70];
+        }
+        $categorys = SysCategory::whereIn('category_id', $categorySuperIds)->get()->toArray();
+        foreach ($categorys as $item) {
+            if (empty($item['category_super_path'])) {
+                $item['category_super_path'] = '#' . $item['category_id'] . '#';
+            } else {
+                $item['category_super_path'] = $item['category_super_path'] . '#' . $item['category_id'] . '#';
+            }
+
+            $categoryIds = SysCategory::where('category_super_path', 'like', '%' . $item['category_super_path'] . '%')->pluck('category_id');
+            $categoryIds = $categoryIds ? $categoryIds->toArray() : [];
+            $categorySuperIds = array_merge($categorySuperIds, $categoryIds);
+        }
+
+        $categoryIds = array_unique($categorySuperIds);
+
+        $goods = Goods::with('sku')
+//            ->where('goods_classify', $category)
+            ->when(!empty($categoryIds), function ($query) use ($categoryIds) {
+                $query->whereIn('join_goods_category_id', $categoryIds);
+            })->when(empty($categoryIds), function ($query) {
+                $query->where('goods_classify', '<>', 'RECHARGE');
+            })->where('goods_status', 'ON')
+            ->select('goods_id', 'goods_name', 'join_goods_category_id')
+            ->get()
+            ->toArray();
+
+        foreach ($goods as &$good) {
+            if (!empty($good['sku'])) {
+                foreach ($good['sku'] as $key => $sku) {
+                    if (!empty($sku['goods_sku_specs_json'])) {
+                        $specsJson = json_decode($sku['goods_sku_specs_json'], true);
+                        $skuTitle = '';
+                        foreach ($specsJson as $item) {
+                            if (is_array($item)) {
+                                $item = implode(',', $item);
+                            }
+                            $skuTitle .= $item . '-';
+                        }
+                        $good['sku'][$key]['goods_sku_id'] = strval($good['sku'][$key]['goods_sku_id']);
+                        $good['sku'][$key]['goods_sku_title'] = rtrim($skuTitle, '-');
+                    }
+                    unset($good['sku'][$key]['goods_sku_specs_json'], $good['sku'][$key]['join_sku_goods_id']);
+                }
+            } else {
+                $good['sku'] = [];
+            }
+
+        }
+
+        return json_success('', $goods);
+    }
+
+    public static function selectPremisesByGoodsId($goodsId)
+    {
+        $goods = Goods::where('goods_id', $goodsId)
+            ->select('goods_id', 'goods_attribute_json')
+            ->first();
+        $premisses = [];
+        if (!empty($goods->goods_attribute_json)) {
+            $attributeJson = json_decode($goods->goods_attribute_json, true);
+            if (isset($attributeJson['premisses'])) {
+                $premisses = SysDept::whereIn('dept_id', $attributeJson['premisses'])
+                    ->select('dept_id', 'dept_name')
+                    ->get()
+                    ->toArray();
+            }
+        }
+
+        return json_success('', $premisses);
+    }
+
+    public static function selectSpecial(Request $request)
+    {
+        $page = $request->get('page');
+        $pageSize = $request->get('pageSize');
+        $goodsName = $request->get('goods_name', '');
+        $categoryId = $request->get('join_goods_category_id', null);
+        if ($categoryId == null) {
+            $categoryId = [65, 43];
+        } elseif (is_string($categoryId)) {
+            $categoryId = [$categoryId];
+        }
+
+        $rows = Goods::with([
+            'category' => function ($query) {
+                $query->select('category_id', 'category_name');
+            },
+            'running' => function ($query) {
+                $query->select('join_running_goods_id', 'goods_running_storage');
+            },
+            'supplier' => function ($query) {
+                $query->select('supplier_id', 'supplier_name');
+            },
+            'user' => function ($query) {
+                $query->select('user_id', 'user_name');
+            }
+        ])->select('goods_id', 'join_goods_category_id', 'join_goods_supplier_id', 'creator_user_id', 'goods_status', 'goods_sales_price', 'goods_category', 'goods_name', 'goods_title', 'goods_cover', 'goods_sort', 'goods_addtimes', 'goods_updatetimes')
+            ->when($goodsName != '', function ($query) use ($goodsName) {
+                $query->where(function ($q) use ($goodsName) {
+                    $q->where('goods_name', 'like', '%' . $goodsName . '%');
+//                        ->OrWhere('goods_title', 'like', '%' . $goodsName . '%');
+                });
+            })->whereIn('join_goods_category_id', $categoryId)
+            ->orderBy('goods_sort', 'DESC')
+            ->orderBy('goods_addtimes', 'DESC')
+            ->forPage($page, $pageSize)
+            ->get()
+            ->toArray();
+        $total = Goods::when($goodsName != '', function ($query) use ($goodsName) {
+            $query->where(function ($q) use ($goodsName) {
+                $q->where('goods_name', 'like', '%' . $goodsName . '%');
+//                    ->OrWhere('goods_title', 'like', '%' . $goodsName . '%');
+            });
+        })->whereIn('join_goods_category_id', $categoryId)->count();
+
+        foreach ($rows as &$row) {
+            $row['goods_cover'] = getenv('STORAGE_DOMAIN') . $row['goods_cover'];
+            if (isset($row['running'])) {
+                $row['running']['goods_running_storage'] = intval($row['running']['goods_running_storage']);
+            }
+        }
+
+        return json_success('', compact('rows', 'page', 'pageSize', 'total'));
+    }
+
+    public static function selectPicking(Request $request)
+    {
+        $page = $request->get('page');
+        $pageSize = $request->get('pageSize');
+        $goodsName = $request->get('goods_name', '');
+
+        $categorySuperId = $request->get('category_super_id', '');
+        $categoryIds = $request->get('join_goods_category_id', []);
+        if (!empty($categorySuperId) && is_array($categoryIds)) {
+            $category = SysCategory::where('category_id', $categorySuperId)->first();
+            if (empty($category->category_super_path)) {
+                $category->category_super_path = '#' . $categorySuperId . '#';
+            } else {
+                $category->category_super_path = $category->category_super_path . '#' . $categorySuperId . '#';
+            }
+            $categoryIds = SysCategory::where('category_super_path', 'like', '%' . $category->category_super_path)->pluck('category_id');
+            $categoryIds = $categoryIds ? $categoryIds->toArray() : [];
+            $categoryIds = array_merge($categoryIds, [$categorySuperId]);
+        } elseif (!is_array($categoryIds)) {
+            $categoryIds = [$categoryIds];
+        }
+
+        $rows = Goods::with([
+            'category' => function ($query) {
+                $query->select('category_id', 'category_name');
+            },
+            'running' => function ($query) {
+                $query->select('join_running_goods_id', 'goods_running_storage');
+            },
+            'supplier' => function ($query) {
+                $query->select('supplier_id', 'supplier_name');
+            },
+            'user' => function ($query) {
+                $query->select('user_id', 'user_name');
+            }
+        ])->select('goods_id', 'join_goods_category_id', 'join_goods_supplier_id', 'creator_user_id', 'goods_status', 'goods_sales_price', 'goods_category', 'goods_name', 'goods_title', 'goods_cover', 'goods_sort', 'goods_addtimes', 'goods_updatetimes')
+            ->when($goodsName != '', function ($query) use ($goodsName) {
+                $query->where(function ($q) use ($goodsName) {
+                    $q->where('goods_name', 'like', '%' . $goodsName . '%')
+                        ->OrWhere('goods_title', 'like', '%' . $goodsName . '%');
+                });
+            })->whereIn('join_goods_category_id', $categoryIds)
+            ->orderBy('goods_sort', 'DESC')
+            ->orderBy('goods_addtimes', 'DESC')
+            ->forPage($page, $pageSize)
+            ->get()
+            ->toArray();
+        $total = Goods::when($goodsName != '', function ($query) use ($goodsName) {
+            $query->where(function ($q) use ($goodsName) {
+                $q->where('goods_name', 'like', '%' . $goodsName . '%')
+                    ->OrWhere('goods_title', 'like', '%' . $goodsName . '%');
+            });
+        })->whereIn('join_goods_category_id', $categoryIds)
+            ->count();
+
+        foreach ($rows as &$row) {
+            $row['goods_cover'] = getenv('STORAGE_DOMAIN') . $row['goods_cover'];
+            if (isset($row['running'])) {
+                $row['running']['goods_running_storage'] = intval($row['running']['goods_running_storage']);
+            }
+        }
+
+        return json_success('', compact('rows', 'page', 'pageSize', 'total'));
+    }
+
+    public static function selectPackage(Request $request)
+    {
+        $page = $request->get('page');
+        $pageSize = $request->get('pageSize');
+        $goodsName = $request->get('goods_name', '');
+        $categoryId = $request->get('join_goods_category_id', null);
+
+        $rows = Goods::with([
+            'category' => function ($query) {
+                $query->select('category_id', 'category_name');
+            },
+            'running' => function ($query) {
+                $query->select('join_running_goods_id', 'goods_running_storage');
+            },
+            'supplier' => function ($query) {
+                $query->select('supplier_id', 'supplier_name');
+            },
+            'user' => function ($query) {
+                $query->select('user_id', 'user_name');
+            }
+        ])->select('goods_id', 'join_goods_category_id', 'join_goods_supplier_id', 'creator_user_id', 'goods_status', 'goods_sales_price', 'goods_category', 'goods_name', 'goods_title', 'goods_cover', 'goods_sort', 'goods_addtimes', 'goods_updatetimes')
+            ->when($goodsName != '', function ($query) use ($goodsName) {
+                $query->where(function ($q) use ($goodsName) {
+                    $q->where('goods_name', 'like', '%' . $goodsName . '%')
+                        ->OrWhere('goods_title', 'like', '%' . $goodsName . '%');
+                });
+            })->when($categoryId != null, function ($query) use ($categoryId) {
+                $query->where('join_goods_category_id', $categoryId);
+            })
+            ->where('goods_classify', 'PACKAGE')
+            ->orderBy('goods_sort', 'DESC')
+            ->orderBy('goods_addtimes', 'DESC')
+            ->forPage($page, $pageSize)
+            ->get()
+            ->toArray();
+        $total = Goods::when($goodsName != '', function ($query) use ($goodsName) {
+            $query->where(function ($q) use ($goodsName) {
+                $q->where('goods_name', 'like', '%' . $goodsName . '%')
+                    ->OrWhere('goods_title', 'like', '%' . $goodsName . '%');
+            });
+        })->when($categoryId != null, function ($query) use ($categoryId) {
+            $query->where('join_goods_category_id', $categoryId);
+        })->where('goods_classify', 'PACKAGE')->count();
+
+        foreach ($rows as &$row) {
+            $row['goods_cover'] = getenv('STORAGE_DOMAIN') . $row['goods_cover'];
+            if (isset($row['running'])) {
+                $row['running']['goods_running_storage'] = intval($row['running']['goods_running_storage']);
+            }
+//            if (!empty($row['component'])) {
+//                $ids = [];
+//                $contentList = [];
+//                foreach ($row['component'] as $component) {
+//                    $ids[] = $component['join_component_goods_id'];
+//                    $configJson = json_decode($component['goods_component_config_json'], true);
+//                    $contentList[] = [
+//                        'goods_name' => $configJson['goods_name'] ?? '',
+//                        'goods_sales_price' => $component['goods_component_price'],
+//                        'nbr' => $configJson['nbr'] ?? 0
+//                    ];
+//                }
+//
+//                $row['join_component_goods_id'] = $ids;
+//                $row['goodsContentList'] = $contentList;
+//            }
+        }
+
+        return json_success('', compact('rows', 'page', 'pageSize', 'total'));
+    }
+
+    /**
+     * @Desc 下拉选择服务商品
+     * @Author Gorden
+     * @Date 2024/4/24 13:32
+     *
+     * @param Request $request
+     * @return Response
+     */
+    public static function selectList(Request $request, $goodsClassify = "SERVICE")
+    {
+        $keywords = $request->get('keywords', '');
+        $isSupportAppointment = $request->get('is_support_appointment', '');
+//        if (!$keywords){
+//            return json_success('暂无数据');
+//        }
+
+//        $categoryIds = SysCategory::whereIn('category_super_id', [5, 31, 32, 42, 66, 70, 72])->pluck('category_id');
+
+        $goods = Goods::with('sku')
+//            ->whereIn('join_goods_category_id', $categoryIds)
+            ->when($keywords != '', function ($query) use ($keywords) {
+                $query->where('goods_name', 'like', "%" . $keywords . "%");
+            })
+            ->when($goodsClassify != '', function ($query) use ($goodsClassify) {
+                if ($goodsClassify == 'NOPACKAGE') {
+                    $query->where('goods_classify', '<>', 'PACKAGE');
+                } else if ($goodsClassify == 'SERVICE') {
+                    $query->whereIn('goods_classify', ['SERVICE', 'CHNMED', 'CHNNCD']);
+                } else {
+                    $query->where('goods_classify', $goodsClassify);
+                }
+
+            })
+            ->when($isSupportAppointment != '', function ($query) use ($isSupportAppointment) {
+                $query->where('is_support_appointment', $isSupportAppointment);
+            })
+            ->select('goods_id', 'goods_name', 'goods_sales_price', 'join_goods_category_id', 'goods_attribute_json')
+            ->get()
+            ->toArray();
+
+        foreach ($goods as &$good) {
+            if (!empty($good['sku'])) {
+                foreach ($good['sku'] as $key => $sku) {
+                    if (!empty($sku['goods_sku_specs_json'])) {
+                        $good['sku'][$key]['goods_sku_specs_json'] = json_decode($sku['goods_sku_specs_json']);
+
+                        $skuName = '';
+                        foreach ($good['sku'][$key]['goods_sku_specs_json'] as $specsKey => $skuSpecs) {
+                            if (is_array($skuSpecs)) {
+                                $skuName = $skuName . ' ' . $specsKey . ':' . implode(' ', $skuSpecs) . ';';
+                            } else {
+                                $skuName = $skuName . ' ' . $specsKey . ':' . $skuSpecs . ';';
+                            }
+                        }
+                        $good['sku'][$key]['sku_name'] = $skuName;
+                    }
+                }
+            } else {
+                $good['sku'] = [];
+            }
+            $good['premisses'] = [];
+            if (!empty($good['goods_attribute_json'])) {
+                $attributeJson = json_decode($good['goods_attribute_json'], true);
+                if (isset($attributeJson['premisses'])) {
+                    $premisses = SysDept::when(!empty($attributeJson['premisses']), function ($query) use ($attributeJson) {
+                        $query->whereIn('dept_id', $attributeJson['premisses']);
+                    })->where('dept_category', '营业场所')
+                        ->select('dept_id', 'dept_name')
+                        ->get();
+                    $good['premisses'] = $premisses;
+                }
+            }
+        }
+
+        return json_success('', $goods);
+
+    }
+
+    public static function selectCascaderList(Request $request)
+    {
+        $categoryIds = $request->get('category_id', '');
+        $categorySuperId = $request->get('category_super_id', '');
+        $joinGoodsCategoryId = $request->get('join_goods_category_id', '');
+        $type = $request->get('type', '');
+        if (!$categoryIds && !$categorySuperId && !$joinGoodsCategoryId) {
+            return json_fail('参数异常');
+        }
+        $data = [];
+        $categorys = [];
+        if (!empty($categoryIds)) {
+            $categorys = SysCategory::whereIn('category_id', $categoryIds)
+                ->where('category_status', 'ACTIVED')
+                ->select('category_id as id', 'category_name as name', 'category_super_id as pid', 'category_super_path')
+                ->orderBy('category_sort', 'DESC')
+                ->get()
+                ->toArray();
+            $data = array_merge($data, $categorys);
+        } else if (!empty($categorySuperId)) {
+            $categorys = SysCategory::where('category_super_id', $categorySuperId)
+                ->where('category_status', 'ACTIVED')
+                ->select('category_id as id', 'category_name as name', 'category_super_id as pid', 'category_super_path')
+                ->orderBy('category_sort', 'DESC')
+                ->get()
+                ->toArray();
+            $data = array_merge($data, $categorys);
+        }
+
+        foreach ($categorys as $category) {
+            // if(empty($category['category_super_path'])){
+            $category['category_super_path'] = '#' . $category['id'] . '#';
+            // }
+            $subCategory = SysCategory::where('category_super_path', 'like', '%' . $category['category_super_path'] . '%')
+                ->where('category_status', 'ACTIVED')
+                ->select('category_id as id', 'category_name as name', 'category_super_id as pid', 'category_super_path')
+                ->orderBy('category_sort', 'DESC')
+                ->get()
+                ->toArray();
+            $data = array_merge($data, $subCategory);
+        }
+        if (empty($data) && !empty($joinGoodsCategoryId)) {
+            $goodsCategoryIds = $joinGoodsCategoryId;
+        } else {
+            $goodsCategoryIds = array_column($data, 'id');
+        }
+        $goods = Goods::with([
+            'sku' => function ($query) {
+                $query->where('goods_sku_status', 'ON');
+            }
+        ])
+            ->leftJoin('goods_running', 'goods_running.join_running_goods_id', '=', 'goods.goods_id')
+            ->where('goods_running.goods_running_storage', '>', 0)
+            ->whereIn('join_goods_category_id', $goodsCategoryIds)
+            ->where('goods_status', 'ON');
+
+        $goods = $goods->select('goods_id', 'goods_id as id', 'goods_name as name', 'join_goods_category_id as pid', 'goods_attribute_json', 'goods_classify', 'goods_sales_price', 'goods_cover', 'goods_running.goods_running_storage')
+            ->orderBy('goods_sort', 'DESC')
+            ->orderBy('goods_addtimes', 'DESC')
+            ->get()
+            ->toArray();
+        foreach ($goods as &$good) {
+            $good['goods_cover'] = getenv('STORAGE_DOMAIN') . $good['goods_cover'];
+            $good['goods_running_storage'] = intval($good['goods_running_storage']);
+            $good['nbr'] = 0;
+            if (!empty($good['sku'])) {
+                foreach ($good['sku'] as $key => $sku) {
+                    if (!empty($sku['goods_sku_specs_json'])) {
+                        $good['sku'][$key]['goods_sku_specs_json'] = json_decode($sku['goods_sku_specs_json']);
+
+                        $skuName = '';
+                        foreach ($good['sku'][$key]['goods_sku_specs_json'] as $specsKey => $skuSpecs) {
+                            $keyStr = ($specsKey == '规格') ? '' : ($specsKey . ':');
+                            if (is_array($skuSpecs)) {
+                                $skuName = $skuName . $keyStr . ' ' . implode(' ', $skuSpecs) . '; ';
+                            } else {
+                                $skuName = $skuName . $keyStr . ' ' . $skuSpecs . '; ';
+                            }
+                        }
+                        $good['sku'][$key]['sku_name'] = rtrim($skuName, '; ');
+                    }
+                }
+            } else {
+                $good['sku'] = [];
+            }
+            $good['premisses'] = [];
+            if (!empty($good['goods_attribute_json'])) {
+                $attributeJson = json_decode($good['goods_attribute_json'], true);
+                if (isset($attributeJson['premisses'])) {
+                    $premisses = SysDept::when(!empty($attributeJson['premisses']), function ($query) use ($attributeJson) {
+                        $query->whereIn('dept_id', $attributeJson['premisses']);
+                    })->where('dept_category', '营业场所')
+                        ->select('dept_id', 'dept_name')
+                        ->get();
+                    $good['premisses'] = $premisses;
+                }
+            }
+        }
+
+        $data = array_merge($data, $goods);
+        $tree = new Tree($data);
+        $cascaderData = $tree->getTree();
+
+        foreach ($cascaderData as $key1 => $cascader1) {
+            if (isset($cascader1['children'])) {
+                foreach ($cascader1['children'] as $key2 => $cascader2) {
+                    if (isset($cascader2['children'])) {
+                        foreach ($cascader2['children'] as $key3 => $cascader3) {
+                            if (isset($cascader3['children'])) {
+                                foreach ($cascader3['children'] as $key4 => $cascader4) {
+                                    if (!isset($cascader4['goods_id'])) {
+                                        unset($cascaderData[$key1]['children'][$key2]['children'][$key3]['children'][$key4]);
+                                    }
+                                    if (isset($cascader4['goods_id']) && empty($cascader4['sku'])) {
+                                        unset($cascaderData[$key1]['children'][$key2]['children'][$key3]['children'][$key4]);
+                                    }
+                                }
+                            } else if (!isset($cascader3['goods_id'])) {
+                                unset($cascaderData[$key1]['children'][$key2]['children'][$key3]);
+                            }
+                            if (isset($cascader3['goods_id']) && empty($cascader3['sku'])) {
+                                unset($cascaderData[$key1]['children'][$key2]['children'][$key3]);
+                                continue;
+                            }
+                            if (isset($cascader3['children']) && count($cascaderData[$key1]['children'][$key2]['children']) == 0) {
+                                unset($cascaderData[$key1]['children'][$key2]);
+                            }
+                            if (isset($cascader3['children']) && count($cascaderData[$key1]['children'][$key2]['children'][$key3]['children']) > 0) {
+                                $cascaderData[$key1]['children'][$key2]['children'][$key3]['children'] = array_values($cascaderData[$key1]['children'][$key2]['children'][$key3]['children']);
+                            }
+                        }
+                    } else if (!isset($cascader2['goods_id'])) {
+                        unset($cascaderData[$key1]['children'][$key2]);
+                    }
+                    if (isset($cascader2['goods_id']) && empty($cascader2['sku'])) {
+                        unset($cascaderData[$key1]['children'][$key2]);
+                        continue;
+                    }
+                    if (isset($cascader2['children']) && count($cascaderData[$key1]['children'][$key2]['children']) == 0) {
+                        unset($cascaderData[$key1]['children'][$key2]);
+                    }
+                    if (isset($cascader2['children']) && isset($cascaderData[$key1]['children'][$key2]) && count($cascaderData[$key1]['children'][$key2]['children']) > 0) {
+                        $cascaderData[$key1]['children'][$key2]['children'] = array_values($cascaderData[$key1]['children'][$key2]['children']);
+                    }
+                }
+            } else if (!isset($cascader1['goods_id'])) {
+                unset($cascaderData[$key1]);
+            }
+            if (isset($cascader1['goods_id']) && empty($cascader1['sku'])) {
+                unset($cascaderData[$key1]);
+                continue;
+            }
+            if (isset($cascader1['children']) && count($cascaderData[$key1]['children']) == 0) {
+
+                unset($cascaderData[$key1]);
+            }
+            if (isset($cascader1['children']) && isset($cascaderData[$key1]) && count($cascaderData[$key1]['children']) > 0) {
+                $cascaderData[$key1]['children'] = array_values($cascaderData[$key1]['children']);
+            }
+        }
+        $cascaderData = array_values($cascaderData);
+
+        return json_success('success', $cascaderData);
+    }
+
+    /**
+     * @Desc 商品详情
+     * @Author Gorden
+     * @Date 2024/3/28 10:25
+     *
+     * @param $goodsId
+     * @return Response
+     */
+    public static function info($goodsId)
+    {
+        try {
+            // 商品主表
+            $main = Goods::with('category')->where('goods_id', $goodsId)->first();
+            if (!empty($main)) {
+                $main = $main->toArray();
+                $main['goods_sku_json'] = json_decode($main['goods_sku_json'], true);
+                $main['specList'] = [];
+                foreach ($main['goods_sku_json'] as $key => $sku) {
+                    $main['specList'][] = [
+                        'label' => $key,
+                        'tags' => $sku
+                    ];
+                }
+
+            } else {
+                $main = [];
+            }
+            // 详情表
+            $detail = GoodsDetail::where('join_detail_goods_id', $goodsId)->first();
+            if (!empty($detail)) {
+                $detail = $detail->toArray();
+            } else {
+                $detail = [];
+            }
+            // 标签表
+            $label = GoodsLabel::where('join_label_goods_id', $goodsId)->first();
+            if (!empty($label)) {
+                $label = $label->toArray();
+            } else {
+                $label = [];
+            }
+            // Running表
+            $running = GoodsRunning::where('join_running_goods_id', $goodsId)->first();
+            if (!empty($running)) {
+                $running = $running->toArray();
+                if (!empty($running['goods_running_off_json']) && is_json($running['goods_running_off_json'])) {
+                    $goodsRunningOffJson = json_decode($running['goods_running_off_json'], true);
+                    $running['goods_off_addtimes'] = isset($goodsRunningOffJson['time']) ? date("Y-m-d H:i", $goodsRunningOffJson['time']) : '';
+                }
+                $running['goods_running_storage'] = !empty($running['goods_running_storage']) ? intval($running['goods_running_storage']) : '';
+                $running['goods_running_sale'] = !empty($running['goods_running_sale']) ? intval($running['goods_running_sale']) : '';
+            } else {
+                $running = [];
+            }
+            // Sku表
+            $skus = GoodsSku::where('join_sku_goods_id', $goodsId)->where('goods_sku_status', 'ON')->get();
+            if (!empty($skus)) {
+                $skus = $skus->toArray();
+                $submitList = [];
+                foreach ($skus as $key => $sku) {
+                    $skuSpecsJson = json_decode($sku['goods_sku_specs_json'], true);
+                    $skuSpecs = '';
+                    $skuNameValue = [];
+                    $i = 1;
+                    foreach ($skuSpecsJson as $k => $item) {
+                        if (is_array($item)) {
+                            $item = implode(',', $item);
+                        }
+                        $skuSpecs = $skuSpecs . $item . ',';
+                        $skuNameKey = 'skuName' . $i;
+                        $skuValueKey = 'skuValue' . $i;
+                        $skuNameValue[$skuNameKey] = $k;
+                        $skuNameValue[$skuValueKey] = $item;
+                        $skuNameValue[$k] = $item;
+                        $i++;
+                    }
+                    $storage = json_decode($sku['goods_sku_storage_json'], true);
+                    $priceStorage = [
+                        'sku_id' => $sku['goods_sku_id'],
+                        'sku' => rtrim($skuSpecs, ',') ?? '',
+                        'stock' => $storage['storage'] ?? '',
+                        'price' => $sku['goods_sku_sales_price'] ?? '',
+                    ];
+
+                    $submitList[] = array_merge($skuNameValue, $priceStorage);
+                }
+                $skus['submitList'] = $submitList;
+            } else {
+                $skus = [];
+            }
+
+            // 合并数据
+            $data = array_merge($main, $detail, $label, $running, ['sku' => $skus]);
+            $data['goods_sku_json_label'] = [];
+
+            $data['goods_label'] = !empty($data['goods_label']) ? explode(',', $data['goods_label']) : [];
+            $data['goods_json'] = $data['goods_json'] ? json_decode($data['goods_json'], true) : [];
+            $data['goods_cover'] = getenv('STORAGE_DOMAIN') . $data['goods_cover'];
+            if (!empty($data['goods_category']) && $data['goods_category'] == 'INDEX') {
+                $data['goods_recommend_index'] = 'INDEX';
+            }
+
+            // 创建者
+            $data['creator_username'] = '';
+            if (!empty($data['creator_user_id'])) {
+                $data['creator_username'] = SysUser::where('user_id', $data['creator_user_id'])->value('user_name');
+            }
+
+            if (!empty($data['goods_detail_slider_json'])) {
+                $data['goods_detail_slider_json'] = json_decode($data['goods_detail_slider_json'], true);
+                // ……
+                if (isset($data['goods_detail_slider_json']['slider'])) {
+                    $data['goods_detail_slider_json'] = explode(',', $data['goods_detail_slider_json']['slider']);
+                }
+
+                $slider = '';
+                foreach ($data['goods_detail_slider_json'] as $item) {
+                    $slider .= getenv('STORAGE_DOMAIN') . $item . ',';
+                }
+                $data['goods_detail_slider_json'] = rtrim($slider, ',');
+            }
+            $extendJson = [];
+            if (!empty($data['goods_attribute_json'])) {
+                $extendJson = json_decode($data['goods_attribute_json'], true);
+                $data['goods_attribute_json'] = $extendJson;
+            }
+            if (!empty($extendJson['coupon'])) {
+                foreach ($extendJson['coupon'] as $key => $coupon) {
+                    $extendJson['coupon'][$key]['icon'] = getenv('STORAGE_DOMAIN') . $coupon['icon'];
+                }
+                $data['coupon_list'] = $extendJson['coupon'];
+            }
+
+            $data['express_json'] = [];
+            if (!empty($data['goods_express_json'])) {
+                $goodsExpressJson = json_decode($data['goods_express_json'], true);
+                if (isset($goodsExpressJson['express']) && $goodsExpressJson['express'] == 'Y') {
+                    $data['express_json'][] = 'express';
+                }
+                if (isset($goodsExpressJson['self']) && $goodsExpressJson['self'] == 'Y') {
+                    $data['express_json'][] = 'self';
+                }
+                if (isset($goodsExpressJson['arrival']) && $goodsExpressJson['arrival'] == 'Y') {
+                    $data['express_json'][] = 'arrival';
+                }
+            }
+            // 详情表数据
+            if (!empty($data['goods_detail_specs_json'])) {
+                $specsJson = json_decode($data['goods_detail_specs_json'], true);
+                foreach ($specsJson as $itemSpecsJson) {
+                    if (isset($itemSpecsJson['key']) && $itemSpecsJson['key'] == '课时') {
+                        $data['curriculum']['period'] = $itemSpecsJson['val'];
+                    } elseif (isset($itemSpecsJson['key']) && $itemSpecsJson['key'] == '群体') {
+                        $data['curriculum']['group'] = $itemSpecsJson['val'];
+                    } elseif (isset($itemSpecsJson['key']) && $itemSpecsJson['key'] == '课程') {
+                        $data['curriculum']['course'] = $itemSpecsJson['val'];
+                    }
+                }
+            }
+
+            return json_success('', $data);
+        } catch (\Exception $e) {
+            dump($e->getMessage());
+            return json_fail("查询错误~");
+        }
+    }
+
+    /**
+     * @Desc 添加商品
+     * @Author Gorden
+     * @Date 2024/3/11 10:20
+     *
+     * @param $params
+     * @return Response
+     */
+    public static function insert($params): Response
+    {
+        Db::beginTransaction();
+        try {
+            $params['goods_id'] = "GD" . date('ymdHi') . random_string(4, 'up');
+            // 主表
+            self::mainInsert($params);
+            // 商品详情表
+            self::detailInsert($params);
+            // 商品标签表
+            self::labelInsert($params);
+            // 产品运行控制信息表
+            self::goodsRunningInsert($params);
+            // sku表
+            self::goodsSkuSet($params, 'insert');
+            // 待上架状态,上架时间大于当前时间
+            if ($params['goods_status'] == 'PENDING' && strtotime($params['goods_on_addtimes']) > time()) {
+                $redis = Redis::connection();
+                $key = date('YmdHi', strtotime($params['goods_on_addtimes']));
+                $redis->sAdd(Goods::LISTING_KEY_PREFIX . $key, $params['goods_id']);
+            }
+            // 自动下架
+            if (!empty($params['goods_running_off_type']) && $params['goods_running_off_type'] == 'T' && !empty($params['goods_off_addtimes'])) {
+                $redis = Redis::connection();
+                $key = Goods::LISTING_OFF_KEY_PREFIX . date('YmdHi', strtotime($params['goods_off_addtimes']));
+                $redis->sAdd($key, $params['goods_id']);
+            }
+            Db::commit();
+        } catch (\PDOException $e) {
+            Db::rollBack();
+            dump($e->getFile() . '(' . $e->getLine() . '):' . $e->getMessage());
+            return json_fail('数据写入失败~');
+        } catch (BusinessException $e) {
+            Db::rollBack();
+            dump($e->getFile() . '(' . $e->getLine() . '):' . $e->getMessage());
+            return json_fail($e->getMessage());
+        } catch (\Exception $e) {
+            Db::rollBack();
+            dump($e->getTrace());
+            return json_fail('数据写入失败~');
+        }
+
+        _syslog("添加商品", "商品名【" . $params['goods_name'] . "】");
+
+        return json_success('success');
+    }
+
+    public static function insertRecharge($params)
+    {
+        try {
+            Db::beginTransaction();
+            $goods = new Goods();
+            $goods->goods_id = "GD" . date('ymdHi') . random_string(4, 'up');
+            $goods->join_goods_category_id = 59;
+            $goods->goods_classify = 'RECHARGE';
+            $goods->goods_status = $params['goods_status'];
+            $goods->goods_sort = $params['goods_sort'];
+            $goods->goods_category = $params['goods_category'];
+            $goods->goods_name = $params['goods_name'];
+            $goods->goods_market_price = $params['goods_sales_price'];
+            $goods->goods_sales_price = $params['goods_sales_price'];
+            $goods->goods_sku_json = json_encode(['规格' => [$params['goods_sales_price'] . '元']]);
+            $goods->goods_attribute_json = json_encode(['added' => ['nbr' => $params['goods_rate'] / 100, 'mode' => 'rate'], 'min-count' => 1]);
+            $goods->goods_cover = '/images/app/common/null-service.png';
+            $goods->goods_process_json = json_encode(['mode' => 'do_shopping']);
+            $goods->goods_addtimes = time();
+            $goods->save();
+
+            $sku = new GoodsSku();
+            $sku->join_sku_goods_id = $goods->goods_id;
+            $sku->goods_sku_status = $params['goods_status'];
+            $sku->goods_sku_specs_json = json_encode(['规格' => $params['goods_sales_price'] . '元']);
+            $sku->goods_sku_market_price = $params['goods_sales_price'];
+            $sku->goods_sku_sales_price = $params['goods_sales_price'];
+            $sku->goods_sku_storage_json = json_encode(['storage' => 9999]);
+            $sku->save();
+
+            Db::commit();
+
+            return json_success('success');
+        } catch (\Exception $e) {
+
+            Db::rollBack();
+
+            return json_fail('添加充值产品失败');
+        }
+    }
+
+    public static function updateRecharge($params)
+    {
+        try {
+            Db::beginTransaction();
+            $goods = Goods::where('goods_id', $params['goods_id'])->first();
+            if (!$goods) {
+                return json_fail("数据异常");
+            }
+            $goods->goods_market_price = $params['goods_sales_price'];
+            $goods->goods_sales_price = $params['goods_sales_price'];
+            $goods->goods_status = $params['goods_status'];
+            $goods->goods_sku_json = json_encode(['规格' => [$params['goods_sales_price'] . '元']]);
+            $goods->goods_sort = $params['goods_sort'];
+            if (!empty($goods->goods_attribute_json)) {
+                $attributeJson = json_decode($goods->goods_attribute_json, true);
+                $attributeJson['added']['nbr'] = $params['goods_rate'] / 100;
+                $goods->goods_attribute_json = json_encode($attributeJson);
+            }
+            $goods->save();
+            $sku = GoodsSku::where('join_sku_goods_id', $params['goods_id'])->where('goods_sku_status', 'ON')->first();
+            $sku->goods_sku_status = $params['goods_status'];
+            $sku->goods_sku_specs_json = json_encode(['规格' => $params['goods_sales_price'] . '元']);
+            $sku->goods_sku_market_price = $params['goods_sales_price'];
+            $sku->goods_sku_sales_price = $params['goods_sales_price'];
+            $sku->save();
+
+            Db::commit();
+
+            return json_success("success");
+        } catch (\Exception $e) {
+            Db::rollBack();
+            dump($e->getMessage());
+            return json_fail('编辑充值产品失败');
+        }
+    }
+
+    public static function insertPackage($params): Response
+    {
+        Db::beginTransaction();
+        try {
+            $params['goods_id'] = "GD" . date('ymdHi') . random_string(4, 'up');
+            // 主表
+            self::mainInsert($params);
+            // 商品详情表
+            self::detailInsert($params);
+            // 套包组件表
+            self::componentUpdate($params, 'insert');
+            // 商品标签表
+            self::labelInsert($params);
+            // 产品运行控制信息表
+            self::goodsRunningInsert($params);
+            // sku表
+//            self::goodsSkuSet($params, 'insert');
+            // 待上架状态,上架时间大于当前时间
+            if ($params['goods_status'] == 'PENDING' && strtotime($params['goods_on_addtimes']) > time()) {
+                $redis = Redis::connection();
+                $key = date('YmdHi', strtotime($params['goods_on_addtimes']));
+                $redis->sAdd(Goods::LISTING_KEY_PREFIX . $key, $params['goods_id']);
+            }
+            Db::commit();
+        } catch (\PDOException $e) {
+            Db::rollBack();
+            dump($e->getMessage());
+            return json_fail('数据写入失败~');
+        } catch (BusinessException $e) {
+            Db::rollBack();
+            dump($e->getMessage());
+            return json_fail($e->getMessage());
+        } catch (\Exception $e) {
+            Db::rollBack();
+            dump($e->getTrace());
+            return json_fail('数据写入失败~');
+        }
+
+        _syslog("添加套餐", "商品名【" . $params['goods_name'] . "】");
+
+        return json_success('success');
+    }
+
+    public static function update($params)
+    {
+        Db::beginTransaction();
+        try {
+            // 主表
+            self::mainUpdate($params);
+            // 商品详情表
+            self::detailUpdate($params);
+            // 商品标签表
+            self::labelUpdate($params);
+            // 产品运行控制信息表
+            self::goodsRunningUpdate($params);
+            // sku表
+            self::goodsSkuSet($params, 'update');
+
+            Db::commit();
+        } catch (BusinessException $e) {
+            Db::rollBack();
+            return json_fail($e->getMessage());
+        } catch (\Exception $e) {
+            Db::rollBack();
+            return json_fail('数据更新失败~');
+        }
+
+        _syslog("编辑商品", "商品名【" . $params['goods_name'] . "】" ?? "商品ID:【" . $params['goods_id'] . "】");
+
+        return json_success('success');
+    }
+
+    public static function changeStatus($params)
+    {
+        try {
+            Goods::where('goods_id', $params['goods_id'])->update(['goods_status' => $params['goods_status']]);
+
+            return json_success('修改成功');
+        } catch (\Exception $e) {
+            return json_fail('修改状态失败');
+        }
+    }
+
+
+    public static function updatePackage($params)
+    {
+        Db::beginTransaction();
+        try {
+            // 主表
+            self::mainUpdate($params);
+            // 商品详情表
+            self::detailUpdate($params);
+            // 套包组件表
+            self::componentUpdate($params, 'update');
+            // 商品标签表
+            self::labelUpdate($params);
+            // 产品运行控制信息表
+            self::goodsRunningUpdate($params);
+            // sku表
+            self::goodsSkuSet($params, 'update');
+
+            Db::commit();
+        } catch (BusinessException $e) {
+            Db::rollBack();
+            return json_fail($e->getMessage());
+        } catch (\Exception $e) {
+            Db::rollBack();
+            dump($e->getTrace());
+            return json_fail('数据更新失败~');
+        }
+        _syslog("编辑套餐", "商品名【" . $params['goods_name'] . "】" ?? "商品ID:【" . $params['goods_id'] . "】");
+
+        return json_success('success');
+    }
+
+    /**
+     * @Desc 删除商品
+     * @Author Gorden
+     * @Date 2024/3/28 13:20
+     *
+     * @param $ids
+     * @return Response
+     */
+    public static function delete($ids)
+    {
+        if (!$ids) {
+            return json_fail("数据错误~");
+        }
+        if (!is_array($ids)) {
+            $ids = [$ids];
+        }
+
+        $goods = Goods::whereIn('goods_id', $ids)->get()->toArray();
+        if (!$goods) {
+            return json_fail("数据错误~");
+        }
+
+        // 是否在套包里
+        if (GoodsComponent::whereIn('join_component_goods_id', $ids)->exists()) {
+            return json_fail("当前商品存在于套包中,请先在套包中删除");
+        }
+        // 是否已被购买过
+        if (OrderSheet::whereIn('join_sheet_goods_id', $ids)->exists()) {
+            return json_fail("当前商品已有购买历史,如不在APP显示,请选择【下架】操作");
+        }
+        // 是否预约过
+        if (Appointment::whereIn('join_appointment_goods_id', $ids)->exists()) {
+
+            return json_fail("当前商品已有预约历史,如不在APP显示,请选择【下架】操作");
+        }
+
+        Db::beginTransaction();
+        try {
+            Goods::whereIn('goods_id', $ids)->delete();
+            GoodsDetail::whereIn('join_detail_goods_id', $ids)->delete();
+            GoodsLabel::whereIn('join_label_goods_id', $ids)->delete();
+            GoodsRunning::whereIn('join_running_goods_id', $ids)->delete();
+            GoodsSku::whereIn('join_sku_goods_id', $ids)->delete();
+
+            Db::commit();
+
+            _syslog("删除商品 / 套餐", "ID:【" . implode(',', $ids) . "】", $goods);
+
+            return json_success("商品删除成功");
+        } catch (\Exception $e) {
+            Db::rollBack();
+
+            return json_fail("商品删除失败~");
+        }
+    }
+
+    /**
+     * @Desc 商品主表
+     * @Author Gorden
+     * @Date 2024/3/11 11:20
+     *
+     * @param $params
+     * @return mixed|string
+     * @throws BusinessException
+     */
+    public static function mainInsert($params)
+    {
+        if (!empty($params['goods_cover'])) {
+            $params['goods_cover'] = str_replace(getenv('STORAGE_DOMAIN'), '', $params['goods_cover']);
+        }
+        // 如果产品是待处理状态
+        if ($params['goods_status'] == 'PENDING') {
+            if (strtotime($params['goods_on_addtimes']) <= time()) {
+                $params['goods_status'] = 'ON';
+            }
+        }
+        $category = SysCategory::where('category_id', $params['join_goods_category_id'])->first();
+        if (!$category) {
+            throw new BusinessException("产品分类不存在~");
+        }
+        if (empty($params['goods_category'])) {
+            $params['goods_category'] = $category->category_classify;
+        }
+
+        try {
+            $model = new Goods();
+            $model->goods_id = $params['goods_id'];
+            $model->join_goods_category_id = $params['join_goods_category_id'] ?? 0;
+            $model->join_goods_supplier_id = $params['join_goods_supplier_id'] ?? 0;
+            $model->goods_classify = $params['goods_classify'] ?? '';
+            $model->goods_status = $params['goods_status'] ?? '';
+            $model->goods_category = $params['goods_category'] ?? '';
+//            $model->goods_prefix = $params['goods_prefix'] ?? 】($category->category_name ? '【' . $category->category_name . '' : '');
+            $model->goods_prefix = $params['goods_prefix'] ?? '';
+            $model->goods_name = $params['goods_name'];
+            $model->goods_market_price = $params['goods_market_price'] ?? 0;
+            $model->goods_sales_price = $params['goods_sales_price'] ?? 0;
+            $model->goods_sku_json = !empty($params['goods_sku_json_label']) ? json_encode($params['goods_sku_json_label']) : json_encode(['规格' => ['标准']]);
+            $model->goods_attribute_json = !empty($params['goods_attribute_json']) ? $params['goods_attribute_json'] : '[]';
+            $model->goods_title = $params['goods_title'] ?? '';
+            $model->goods_cover = $params['goods_cover'] ?? '';
+            $model->goods_on_addtimes = isset($params['goods_on_addtimes']) ? strtotime($params['goods_on_addtimes']) : null;
+            $model->goods_sort = $params['goods_sort'] ?? null;
+            $model->goods_groupby = $params['goods_groupby'] ?? '';
+            $model->goods_remark = $params['goods_remark'] ?? '';
+            $model->goods_extend_json = $params['goods_extend_json'] ?? '{}';
+            $model->is_support_appointment = $params['is_support_appointment'] ?? 'N';
+            $model->creator_user_id = JwtToken::getCurrentId();
+            $model->goods_addtimes = time();
+            $model->goods_updatetimes = time();
+            // {"express":"Y","self":"Y","arrival":"Y"}
+            $expressJson = [];
+            if (!empty($params['express_json'])) {
+                if (in_array('express', $params['express_json'])) {
+                    $expressJson['express'] = 'Y';
+                } else {
+                    $expressJson['express'] = 'N';
+                }
+                if (in_array('self', $params['express_json'])) {
+                    $expressJson['self'] = 'Y';
+                } else {
+                    $expressJson['self'] = 'N';
+                }
+                if (in_array('arrival', $params['express_json'])) {
+                    $expressJson['arrival'] = 'Y';
+                } else {
+                    $expressJson['arrival'] = 'N';
+                }
+
+                $model->goods_express_json = json_encode($expressJson);
+            }
+
+            if (!empty($params['is_support_appointment']) && $params['is_support_appointment'] == 'Y' && !empty($params['appointment_times']) && $params['goods_category'] != 'TRAVEL') {
+                $times = [];
+                $attributeJsonTimeArr = [];
+                $personTotal = 0;
+                foreach ($params['appointment_times'] as $time) {
+                    $attributeJsonTimeArr[] = strtotime(date('Y-m-d ') . $time['appointmentTimeStart']);
+                    $attributeJsonTimeArr[] = strtotime(date('Y-m-d ') . $time['appointmentTimeEnd']);
+                    $personTotal += $time['person'];
+                    $times[$time['appointmentTimeStart']] = [
+                        'person' => $time['person'],
+                        'duration' => $time['appointmentTimeStart'] . '-' . $time['appointmentTimeEnd']
+                    ];
+                }
+                $attributeJsonTime = date('H:i', min($attributeJsonTimeArr)) . '至' . date('H:i', max($attributeJsonTimeArr));
+
+                $newDates = [];
+                foreach ($params['dates'] as $date) {
+                    $key = self::$week[$date];
+                    $newDates[$key] = $date;
+                }
+                ksort($newDates);
+
+
+                $currentDate = current($newDates);
+                $lastDate = end($newDates);
+
+                $attributeJsonDate = '';
+                if (self::$week[$lastDate] - self::$week[$currentDate] + 1 > count($newDates)) {
+                    $attributeJsonDate = implode(',', $newDates);
+                } else if (self::$week[$lastDate] - self::$week[$currentDate] + 1 == count($newDates)) {
+                    $attributeJsonDate = $currentDate . '至' . $lastDate;
+                }
+
+                // if (isset($params['work_time'])){
+                //     $workTimeStart = date('H:i',strtotime($params['work_time'][0]));
+                //     $workTimeEnd = date('H:i',strtotime($params['work_time'][1]));
+                //     $attributeJsonTime = $workTimeStart.'至'.$workTimeEnd;
+                // }
+
+                $attributeJson = [
+                    'icon' => $model->goods_cover,
+                    'date' => $attributeJsonDate,
+                    // 'time' => $attributeJsonTime,
+                    'dates' => $newDates ? array_values($newDates) : [],
+                    'times' => $times,
+                    'person' => $personTotal
+                ];
+                // if(isset($params['address'])){
+                //     $attributeJson['address'] = $params['address'];
+                // }
+                // if (isset($params['min_count'])){
+                //     $attributeJson['min-count'] = $params['min_count'];
+                // }else{
+                //     $attributeJson['min-count'] = 1;
+                // }
+                // if (isset($params['teachers'])){
+                //     $attributeJson['teachers'] = $params['teachers'];
+                // }
+                if (!empty($params['appointment_label'])) {
+                    $attributeJson['label'] = $params['appointment_label'];
+                }
+                // if (!empty($params['address'])) {
+                //     $attributeJson['address'] = $params['address'];
+                // }
+                // if (!empty($params['position'])){
+                //     $attributeJson['position'] = $params['position'];
+                // }
+                // if (isset($params['goods_service_premises'])){
+                //     $attributeJson['service_premises_id'] = $params['goods_service_premises'];
+                // }
+                $model->goods_attribute_json = json_encode($attributeJson, JSON_UNESCAPED_UNICODE);
+
+//                $times = [];
+//                foreach ($params['appointment_times'] as $time) {
+//                    $times[$time['appointmentTimeStart']] = [
+//                        'person' => $time['person'],
+//                        'duration' => $time['appointmentTimeStart'] . '-' . $time['appointmentTimeEnd']
+//                    ];
+//                }
+//                $model->goods_attribute_json = json_encode([
+//                    'icon' => '',
+//                    'dates' => $params['dates'] ?? [],
+//                    'times' => $times
+//                ]);
+            }
+            if (!empty($params['is_support_appointment']) && $params['is_support_appointment'] == 'Y' && !empty($params['appointment_times']) && $params['goods_category'] == 'TRAVEL') {
+                if (!empty($model->goods_attribute_json) && !is_array($model->goods_attribute_json)) {
+                    $attributeJson = json_decode($model->goods_attribute_json, true);
+                } elseif (empty($model->goods_attribute_json)) {
+                    $attributeJson = [];
+                }
+                $attributeJson['travel-day'] = $params['travel_day'];
+                $attributeJson['travel-begin'] = $params['travel_begin'];
+                $attributeJson['travel-night'] = $params['travel_night'];
+                $attributeJson['travel-trans'] = $params['travel_trans'];
+
+                $unixs = [];
+                foreach ($params['appointment_times'] as $times) {
+                    $unix = strtotime($times['days']);
+                    $unixs[$unix] = $times['person'];
+                }
+                ksort($unixs);
+                $months = [];
+                foreach ($unixs as $key => $unix) {
+                    $month = date('Ym', $key);
+                    $day = date('d', $key);
+                    $months[$month][$day] = $unix;
+                }
+                $attributeJson['month'] = $months;
+                $model->goods_attribute_json = json_encode($attributeJson, JSON_UNESCAPED_UNICODE);
+            }
+            if (!empty($params['goods_json']) && $params['join_goods_category_id'] == 65) {
+                $goodsJson = json_decode($params['goods_json'], true);
+//                foreach ($goodsJson as $key => $item) {
+//                    $goodsJson[$key]['color'] = hexToRgb($item['color']);
+//                }
+//
+                $model->goods_json = json_encode($goodsJson);
+            } elseif (!empty($params['goods_json']) && $params['join_goods_category_id'] == 43) {
+                $goodsJson = json_decode($params['goods_json'], true);
+                $newGoodsJson = [];
+                foreach ($goodsJson as $item1) {
+                    if (empty($item1['title'])) {
+                        continue;
+                    }
+                    $newItem1 = [];
+                    foreach ($item1['items'] as $item2) {
+                        $newParams = [];
+                        foreach ($item2['params'] as $param) {
+                            if (!empty($param[0]) || !empty($param[1])) {
+                                $newParams[] = $param;
+                            }
+                        }
+                        $newItem1['items'][$item2['key']] = $newParams;
+                    }
+                    $newItem1['service'] = $item1['service'] ?? '';
+                    $newGoodsJson[$item1['title']] = $newItem1;
+                }
+                $model->goods_json = json_encode($newGoodsJson);
+            } else {
+                $model->goods_json = '[]';
+            }
+
+            if (!empty($params['goods_premisses'])) {
+                $attributeJson = [];
+                if (!empty($model->goods_attribute_json) && !is_array($model->goods_attribute_json)) {
+                    $attributeJson = json_decode($model->goods_attribute_json, true);
+                } elseif (empty($model->goods_attribute_json)) {
+                    $attributeJson = [];
+                }
+                $attributeJson['premisses'] = $params['goods_premisses'];
+                $model->goods_attribute_json = json_encode($attributeJson);
+            }
+
+            if (!empty($params['goods_theme_color']) && !empty($params['goods_theme_icon'])) {
+                if (!empty($model->goods_attribute_json) && !is_array($model->goods_attribute_json)) {
+                    $attributeJson = json_decode($model->goods_attribute_json, true);
+                } elseif (empty($model->goods_attribute_json)) {
+                    $attributeJson = [];
+                }
+                $attributeJson['bg'] = $params['goods_theme_color'];
+                $attributeJson['icon'] = str_replace(getenv('STORAGE_DOMAIN'), '', $params['goods_theme_icon']);
+                $model->goods_attribute_json = json_encode($attributeJson);
+            }
+            if (!empty($params['address'])) {
+                if (!empty($model->goods_attribute_json) && !is_array($model->goods_attribute_json)) {
+                    $attributeJson = json_decode($model->goods_attribute_json, true);
+                } elseif (empty($model->goods_attribute_json)) {
+                    $attributeJson = [];
+                }
+                $attributeJson['address'] = $params['address'];
+                $model->goods_attribute_json = json_encode($attributeJson);
+            }
+            if (!empty($params['position'])) {
+                if (!empty($model->goods_attribute_json) && !is_array($model->goods_attribute_json)) {
+                    $attributeJson = json_decode($model->goods_attribute_json, true);
+                } elseif (empty($model->goods_attribute_json)) {
+                    $attributeJson = [];
+                }
+                $attributeJson['position'] = $params['position'];
+                $model->goods_attribute_json = json_encode($attributeJson);
+            }
+            if (isset($params['goods_service_premises'])) {
+                if (!empty($model->goods_attribute_json) && !is_array($model->goods_attribute_json)) {
+                    $attributeJson = json_decode($model->goods_attribute_json, true);
+                } elseif (empty($model->goods_attribute_json)) {
+                    $attributeJson = [];
+                }
+                $attributeJson['service_premises_id'] = $params['goods_service_premises'];
+                $model->goods_attribute_json = json_encode($attributeJson);
+            }
+            if (isset($params['min_count'])) {
+                if (!empty($model->goods_attribute_json) && !is_array($model->goods_attribute_json)) {
+                    $attributeJson = json_decode($model->goods_attribute_json, true);
+                } elseif (empty($model->goods_attribute_json)) {
+                    $attributeJson = [];
+                }
+                $attributeJson['min-count'] = $params['min_count'];
+                $model->goods_attribute_json = json_encode($attributeJson);
+            }
+            if (isset($params['teachers'])) {
+                if (!empty($model->goods_attribute_json) && !is_array($model->goods_attribute_json)) {
+                    $attributeJson = json_decode($model->goods_attribute_json, true);
+                } elseif (empty($model->goods_attribute_json)) {
+                    $attributeJson = [];
+                }
+                $attributeJson['teachers'] = $params['teachers'];
+                $model->goods_attribute_json = json_encode($attributeJson);
+            }
+            if (isset($params['work_time'])) {
+                if (!empty($model->goods_attribute_json) && !is_array($model->goods_attribute_json)) {
+                    $attributeJson = json_decode($model->goods_attribute_json, true);
+                } elseif (empty($model->goods_attribute_json)) {
+                    $attributeJson = [];
+                }
+
+                $workTimeStart = date('H:i', strtotime($params['work_time'][0]));
+                $workTimeEnd = date('H:i', strtotime($params['work_time'][1]));
+                $attributeJsonTime = $workTimeStart . '至' . $workTimeEnd;
+
+                $attributeJson['time'] = $attributeJsonTime;
+                $model->goods_attribute_json = json_encode($attributeJson);
+            }
+            if (!empty($params['coupon_id']) && !empty($params['coupon_nbr'])) {
+                if (!empty($model->goods_attribute_json) && !is_array($model->goods_attribute_json)) {
+                    $attributeJson = json_decode($model->goods_attribute_json, true);
+                } elseif (empty($model->goods_attribute_json)) {
+                    $attributeJson = [];
+                }
+                $coupons = Coupon::whereIn('coupon_id', $params['coupon_id'])
+                    ->select('coupon_id', 'coupon_name')
+                    ->get()
+                    ->toArray();
+                $couponList = [];
+                foreach ($coupons as $coupon) {
+                    if (isset($params['coupon_nbr'][$coupon['coupon_id']])) {
+                        $couponList[$coupon['coupon_id']] = [
+                            'num' => $params['coupon_nbr'][$coupon['coupon_id']],
+                            'name' => $coupon['coupon_name']
+                        ];
+                    }
+                }
+                $attributeJson['coupon'] = $couponList;
+                $model->goods_attribute_json = json_encode($attributeJson, JSON_UNESCAPED_UNICODE);
+            }
+            if ($model->save()) {
+                return $model->goods_id;
+            }
+            // 异常
+            throw new BusinessException("数据写入失败~");
+        } catch (\Exception $e) {
+            dump($e->getMessage());
+            throw new BusinessException("数据写入失败~");
+        }
+    }
+
+    /**
+     * @Desc 详情表
+     * @Author Gorden
+     * @Date 2024/3/11 11:19
+     *
+     * @param $params
+     * @return void
+     * @throws BusinessException
+     */
+    public static function detailInsert($params)
+    {
+        if (!empty($params['goods_detail_slider_json'])) {
+            $params['goods_detail_slider_json'] = str_replace(getenv('STORAGE_DOMAIN'), '', $params['goods_detail_slider_json']);
+            $params['goods_detail_slider_json'] = json_encode(['slider' => $params['goods_detail_slider_json']]);
+        }
+
+        if (isset($params['curriculum'])) {
+            $params['goods_detail_specs_json'] = json_encode([
+                [
+                    'key' => '课时',
+                    'val' => $params['curriculum']['period'] ?? '',
+                ],
+                [
+                    'key' => '群体',
+                    'val' => $params['curriculum']['group'] ?? '',
+                ],
+                [
+                    'key' => '课程',
+                    'val' => $params['curriculum']['course'] ?? '',
+                ],
+            ]);
+        }
+        try {
+            $model = new GoodsDetail();
+            $model->join_detail_goods_id = $params['goods_id'];
+            $model->goods_detail_code_json = $params['goods_detail_code_json'] ?? '{}';
+            $model->goods_detail_slider_json = $params['goods_detail_slider_json'] ?? '{}';
+            $model->goods_detail_specs_json = $params['goods_detail_specs_json'] ?? '{}';
+            $model->goods_detail_content = $params['goods_detail_content'] ?? '';
+            if (!$model->save()) {
+                // 异常
+                throw new BusinessException("轮播图/详情数据写入失败~");
+            }
+        } catch (\Exception $e) {
+            dump($e->getMessage());
+            throw new BusinessException("轮播图/详情数据写入失败~");
+        }
+    }
+
+    public static function componentUpdate($params, $type = 'insert')
+    {
+        Db::beginTransaction();
+        try {
+            $goodsSku = '';
+            // 有先删除
+            if ($type == 'update') {
+                GoodsComponent::where('join_component_master_goods_id', $params['goods_id'])->delete();
+                $goodsSku = GoodsSku::where('join_sku_goods_id', $params['goods_id'])->first();
+                if ($goodsSku) {
+                    $goodsSku->goods_sku_market_price = $params['goods_market_price'] ?? 0;
+                    $goodsSku->goods_sku_sales_price = $params['goods_sales_price'] ?? 0;
+                    $goodsSku->save();
+                }
+            }
+            if ($type == 'insert' || !$goodsSku) {
+                Goods::where('goods_id', $params['goods_id'])->update(['goods_sku_json' => '{"规格": ["标准"]}']);
+                $skuData = [
+                    'join_sku_goods_id' => $params['goods_id'],
+                    'goods_sku_status' => 'ON',
+                    'goods_sku_specs_json' => '{"规格": "标准"}',
+                    'goods_sku_title' => "标准" . $params['goods_name'],
+                    'goods_sku_market_price' => $params['goods_market_price'] ?? 0,
+                    'goods_sku_sales_price' => $params['goods_sales_price'] ?? 0,
+                ];
+                GoodsSku::insert($skuData);
+            }
+            $data = [];
+            foreach ($params['goods_content_list'] as $item) {
+                if (!in_array($item['goods_id'], $params['join_component_goods_id'])) {
+                    continue;
+                }
+                $goods = Goods::where('goods_id', $params['goods_id'])->first();
+                if (!$goods) {
+                    continue;
+                }
+
+                $data[] = [
+                    'join_component_master_goods_id' => $params['goods_id'],
+                    'join_component_goods_id' => $item['goods_id'] ?? '',
+                    'join_component_goods_sku_id' => $item['sku_id'] ?? '',
+                    'goods_component_price' => $item['goods_sales_price'] ?? '',
+                    'goods_component_cover' => $goods->goods_cover,
+                    'goods_component_json' => json_encode(['goods_name' => $item['goods_name'], 'nbr' => $item['nbr'], 'sku_id' => $item['sku_id'] ?? '']),
+                    'goods_component_addtimes' => time()
+                ];
+            }
+
+            if ($data) {
+                GoodsComponent::insert($data);
+            }
+            Db::commit();
+        } catch (\Exception $e) {
+            Db::rollBack();
+            dump($e->getMessage());
+            throw new BusinessException("数据写入失败~");
+        }
+    }
+
+    /**
+     * @Desc 标签表
+     * @Author Gorden
+     * @Date 2024/3/11 11:32
+     *
+     * @param $params
+     * @return void
+     * @throws BusinessException
+     */
+    public static function labelInsert($params)
+    {
+        $model = new GoodsLabel();
+        $model->join_label_goods_id = $params['goods_id'];
+        $model->goods_label = $params['goods_label'] ? implode(',', $params['goods_label']) : '';
+        $model->goods_label_extend_json = !empty($params['goods_label_extend_json']) ? $params['goods_label_extend_json'] : '{}';
+        if (!$model->save()) {
+            // 异常
+            throw new BusinessException('数据写入失败~');
+        }
+    }
+
+    /**
+     * @Desc 产品运行控制信息表
+     * @Author Gorden
+     * @Date 2024/3/11 11:38
+     *
+     * @param $params
+     * @return void
+     * @throws BusinessException
+     */
+    public static function goodsRunningInsert($params)
+    {
+        try {
+            $model = new GoodsRunning();
+            $model->join_running_goods_id = $params['goods_id'];
+            $model->goods_running_storage = $params['goods_running_storage'] ?? 0;
+            $model->goods_running_sale = $params['goods_running_sale'] ?? 0;
+            $model->goods_running_off_type = !empty($params['goods_running_off_type']) ? $params['goods_running_off_type'] : '';
+            $model->goods_running_off_json = !empty($params['goods_running_off_type']) && $params['goods_running_off_type'] == 'T' && !empty($params['goods_off_addtimes']) ? json_encode(['time' => strtotime($params['goods_off_addtimes'])]) : '[]';
+            if (!$model->save()) {
+                throw new BusinessException('数据写入失败');
+            }
+        } catch (\Exception $e) {
+            dump($e->getMessage());
+            throw new BusinessException('数据写入失败');
+        }
+    }
+
+    /**
+     * @Desc SKU
+     * @Author Gorden
+     * @Date 2024/3/11 12:01
+     *
+     * @param $params
+     * @return void
+     * @throws BusinessException
+     */
+    public static function skuInsert($params)
+    {
+        $model = new GoodsSku();
+        $model->join_sku_goods_id = $params['goods_id'];
+        $model->goods_sku_status = $params['goods_sku_status'];
+        $model->goods_sku_specs_json = $params['goods_sku_specs_json'];
+        $model->goods_sku_title = $params['goods_sku_title'];
+        $model->goods_sku_images_json = $params['goods_sku_images_json'];
+        $model->goods_sku_content = $params['goods_sku_content'];
+        $model->goods_sku_market_price = $params['goods_sku_market_price'];
+        $model->goods_sku_sales_price = $params['goods_sku_sales_price'];
+        $model->goods_sku_storage_json = $params['goods_sku_storage_json'];
+        $model->goods_sku_service_json = $params['goods_sku_service_json'];
+        $model->goods_sku_extend_json = $params['goods_sku_extend_json'];
+        if (!$model->save()) {
+            throw new BusinessException('规格数据写入失败~');
+        }
+    }
+
+    /**
+     * @Desc
+     * @Author Gorden
+     * @Date 2024/3/12 8:44
+     *
+     * @param $params
+     * @return void
+     * @throws BusinessException
+     */
+    public static function mainUpdate($params)
+    {
+        try {
+            $data = self::inputFilter($params, new Goods());
+            if (!empty($data['goods_cover'])) {
+                $data['goods_cover'] = str_replace(getenv('STORAGE_DOMAIN'), '', $data['goods_cover']);
+            }
+            $data['goods_on_addtimes'] = isset($data['goods_on_addtimes']) ? strtotime($data['goods_on_addtimes']) : 0;
+            $data['goods_sku_json'] = !empty($params['goods_sku_json_label']) ? json_encode($params['goods_sku_json_label']) : json_encode(['规格' => ['标准']]);
+
+            $row = Goods::find($data['goods_id']);
+            if ($row->join_goods_category_id != $data['join_goods_category_id']) {
+                $category = SysCategory::where('category_id', $params['join_goods_category_id'])->first();
+                if (!$category) {
+                    throw new BusinessException("产品分类不存在~");
+                }
+                $data['goods_category'] = $category->category_classify ?? '';
+                $data['goods_prefix'] = $data['goods_prefix'] ?? ($category->category_name ? '【' . $category->category_name . '】' : '');
+            }
+
+            $expressJson = [];
+            if (!empty($params['express_json'])) {
+                if (in_array('express', $params['express_json'])) {
+                    $expressJson['express'] = 'Y';
+                } else {
+                    $expressJson['express'] = 'N';
+                }
+                if (in_array('self', $params['express_json'])) {
+                    $expressJson['self'] = 'Y';
+                } else {
+                    $expressJson['self'] = 'N';
+                }
+                if (in_array('arrival', $params['express_json'])) {
+                    $expressJson['arrival'] = 'Y';
+                } else {
+                    $expressJson['arrival'] = 'N';
+                }
+
+                $data['goods_express_json'] = json_encode($expressJson);
+            }
+            $attributeJson = [];
+            if (!empty($row->goods_attribute_json)) {
+                $attributeJson = json_decode($row->goods_attribute_json, true);
+            }
+            if (!empty($params['chooseCoupons'])) {
+                $couponList = [];
+                foreach ($params['chooseCoupons'] as $chooseCoupon) {
+                    $coupon = Coupon::where('coupon_id', $chooseCoupon['coupon_id'])
+                        ->select('coupon_id', 'coupon_name')
+                        ->first();
+                    $couponList[$coupon->coupon_id] = [
+                        'coupon_id' => $coupon->coupon_id,
+                        'num' => $chooseCoupon['num'],
+                        'name' => $coupon->coupon_name,
+                        'icon' => str_replace(getenv("STORAGE_DOMAIN"), '', str_replace('/thumb','',$chooseCoupon['icon'])),
+                        'unit' => '张'
+                    ];
+                }
+                $attributeJson['coupon'] = $couponList;
+            }
+            if (!empty($params['attribute_account'])) {
+                $attributeJson['account'] = $params['attribute_account'];
+            }
+            if (!empty($params['attribute_control'])) {
+                $attributeJson['control'] = $params['attribute_control'];
+            }
+
+            $data['goods_attribute_json'] = json_encode($attributeJson, JSON_UNESCAPED_UNICODE);
+
+            foreach ($data as $key => $val) {
+                $row->{$key} = $val;
+            }
+            $row->goods_updatetimes = time();
+            $row->updator_user_id = JwtToken::getCurrentId();
+            $row->save();
+        } catch (BusinessException $e) {
+            throw new BusinessException($e->getMessage());
+        } catch (\Exception $e) {
+            dump($e->getTrace());
+            throw new BusinessException('数据更新异常~1');
+        }
+    }
+
+    /**
+     * @Desc
+     * @Author Gorden
+     * @Date 2024/3/12 9:57
+     *
+     * @param $params
+     * @return void
+     * @throws BusinessException
+     */
+    public static function detailUpdate($params)
+    {
+        try {
+            $data = self::inputFilter($params, new GoodsDetail());
+            if (!empty($data['goods_detail_slider_json'])) {
+                $data['goods_detail_slider_json'] = str_replace(getenv('STORAGE_DOMAIN'), '', $data['goods_detail_slider_json']);
+                $data['goods_detail_slider_json'] = json_encode(['slider' => $data['goods_detail_slider_json']]);
+            }
+            if (isset($params['curriculum'])) {
+                $data['goods_detail_specs_json'] = json_encode([
+                    [
+                        'key' => '课时',
+                        'val' => $params['curriculum']['period'] ?? '',
+                    ],
+                    [
+                        'key' => '群体',
+                        'val' => $params['curriculum']['group'] ?? '',
+                    ],
+                    [
+                        'key' => '课程',
+                        'val' => $params['curriculum']['course'] ?? '',
+                    ],
+                ]);
+            }
+            // 根据goods_id 查详情ID
+            $detail = GoodsDetail::where('join_detail_goods_id', $params['goods_id'])->first();
+            if ($detail) {
+                self::doUpdate($detail->join_detail_goods_id, $data, new GoodsDetail());
+            } else {
+                $data['join_detail_goods_id'] = $params['goods_id'];
+                GoodsDetail::insert($data);
+            }
+        } catch (BusinessException $e) {
+            throw new BusinessException($e->getMessage());
+        } catch (\Exception $e) {
+            dump($e->getMessage());
+            throw new BusinessException('轮播图/详情数据更新异常~');
+        }
+    }
+
+    /**
+     * @Desc
+     * @Author Gorden
+     * @Date 2024/3/12 9:58
+     *
+     * @param $params
+     * @return void
+     * @throws BusinessException
+     */
+    public static function labelUpdate($params)
+    {
+        try {
+            $data = self::inputFilter($params, new GoodsLabel());
+            // 根据goods_id 查详情ID
+            $detail = GoodsLabel::where('join_label_goods_id', $params['goods_id'])->first();
+            if ($detail) {
+                self::doUpdate($detail->goods_label_id, $data, new GoodsLabel());
+            } else {
+                $data['join_label_goods_id'] = $params['goods_id'];
+                GoodsLabel::insert($data);
+            }
+        } catch (BusinessException $e) {
+            throw new BusinessException($e->getMessage());
+        } catch (\Exception $e) {
+            dump($e->getMessage());
+            throw new BusinessException('数据更新异常~3');
+        }
+    }
+
+    /**
+     * @Desc
+     * @Author Gorden
+     * @Date 2024/3/12 9:59
+     *
+     * @param $params
+     * @return void
+     * @throws BusinessException
+     */
+    public static function goodsRunningUpdate($params)
+    {
+        try {
+            $data = self::inputFilter($params, new GoodsRunning());
+            // 根据goods_id 查详情ID
+            $detail = GoodsRunning::where('join_running_goods_id', $params['goods_id'])->first();
+            if (!empty($params['goods_running_off_type']) && $params['goods_running_off_type'] == 'T') {
+                $redis = Redis::connection();
+                if (!empty($detail->goods_running_off_json)) {
+                    $goodsRunningOffJson = json_decode($detail->goods_running_off_json, true);
+                    if (isset($goodsRunningOffJson['time'])) {
+                        $oldKey = Goods::LISTING_OFF_KEY_PREFIX . date('YmdHi', $goodsRunningOffJson['time']);
+                        $goodsRunningOffJson['time'] = strtotime($params['goods_off_addtimes']);
+                        $data['goods_running_off_json'] = json_encode($goodsRunningOffJson);
+                        // 有老的下架时间,删除老的
+                        $redis->srem($oldKey, $params['goods_id']);
+                    } else {
+                        $goodsRunningOffJson['time'] = strtotime($params['goods_off_addtimes']);
+                        $data['goods_running_off_json'] = json_encode($goodsRunningOffJson);
+                    }
+                } else {
+                    $data['goods_running_off_json'] = json_encode(['time' => strtotime($params['goods_off_addtimes'])]);
+                }
+                // 加入自动下架
+                $newKey = Goods::LISTING_OFF_KEY_PREFIX . date('YmdHi', strtotime($params['goods_off_addtimes']));
+                $redis->sAdd($newKey, $params['goods_id']);
+
+            } else if (!empty($params['goods_running_off_type']) && !empty($detail->goods_running_off_type) && $params['goods_running_off_type'] == 'H' && $detail->goods_running_off_type == 'T') {
+                $goodsRunningOffJson = json_decode($detail->goods_running_off_json, true);
+                if (isset($goodsRunningOffJson['time'])) {
+                    $oldKey = Goods::LISTING_OFF_KEY_PREFIX . date('YmdHi', $goodsRunningOffJson['time']);
+                    $redis = Redis::connection();
+                    $redis->srem($oldKey, $params['goods_id']);
+                }
+            }
+            if ($detail) {
+                self::doUpdate($detail->join_running_goods_id, $data, new GoodsRunning());
+            } else {
+                // 兼容老数据……
+                $data['join_running_goods_id'] = $params['goods_id'];
+                GoodsRunning::insert($data);
+            }
+
+        } catch (BusinessException $e) {
+            throw new BusinessException($e->getMessage());
+        } catch (\Exception $e) {
+            dump($e->getMessage());
+            throw new BusinessException('数据更新异常~');
+        }
+    }
+
+    /**
+     * @Desc sku 设置
+     * @Author Gorden
+     * @Date 2024/4/10 10:43
+     *
+     * @param $params
+     * @return void
+     * @throws BusinessException
+     */
+    public static function goodsSkuSet($params, $operation = 'insert')
+    {
+        try {
+            Db::beginTransaction();
+            $skusOldIds = [];
+            if ($operation == 'update') {
+                // 查出所有的
+                $skusOldIds = GoodsSku::where('join_sku_goods_id', $params['goods_id'])->pluck('goods_sku_id', 'goods_sku_id');
+
+                // 删掉原有的
+//                GoodsSku::where('join_sku_goods_id', $params['goods_id'])->delete();
+            }
+            if (empty($skusOldIds) && empty($params['goods_sku_json_value'])) {
+                $skuData = [
+                    'join_sku_goods_id' => $params['goods_id'],
+                    'goods_sku_status' => 'ON',
+                    'goods_sku_specs_json' => '{"规格": "标准"}',
+                    'goods_sku_title' => "标准" . $params['goods_name'],
+                    'goods_sku_market_price' => $params['goods_market_price'] ?? 0,
+                    'goods_sku_sales_price' => $params['goods_sales_price'] ?? 0,
+                ];
+                GoodsSku::insert($skuData);
+            }
+            // 入新的
+            if (!empty($params['goods_sku_json_value'])) {
+                foreach ($params['goods_sku_json_value'] as $item) {
+                    $skus = explode(',', $item['sku']);
+                    $skuArr = [];
+                    for ($i = 1; $i <= count($skus); $i++) {
+                        $skuName = "skuName" . $i;
+                        $key = $item[$skuName];
+                        $skuArr[$key] = $skus[$i - 1];
+                    }
+                    $specsJson = json_encode($skuArr);
+                    $skuTitle = str_replace('-', ',', $item['sku']) . $params['goods_name'];
+                    if ($operation == 'update' && !empty($item['sku_id'])) {
+                        $model = GoodsSku::where('goods_sku_id', $item['sku_id'])->where('goods_sku_status', 'ON')->first();
+                        if (!$model) {
+                            $model = new GoodsSku();
+                        } else {
+                            unset($skusOldIds[$model->goods_sku_id]);
+                        }
+                    } else {
+                        $model = GoodsSku::where('join_sku_goods_id', $params['goods_id'])->where('goods_sku_status', 'ON')->where('goods_sku_title', $skuTitle)->first();
+                        if (!$model) {
+                            $model = new GoodsSku();
+                        } else {
+                            unset($skusOldIds[$model->goods_sku_id]);
+                        }
+
+                    }
+
+                    $model->join_sku_goods_id = $params['goods_id'];
+                    $model->goods_sku_status = $params['goods_status'];
+                    $model->goods_sku_specs_json = $specsJson;
+                    $model->goods_sku_title = $skuTitle;
+                    $model->goods_sku_market_price = $params['goods_market_price'] ?? 0;
+                    $model->goods_sku_sales_price = $item['price'];
+                    $model->goods_sku_storage_json = json_encode(['storage' => $item['stock']]);
+                    $model->save();
+
+                }
+            }
+            if ($operation == 'update' && !empty($skusOldIds)) {
+                // GoodsSku::whereIn('goods_sku_id', $skusOldIds)->delete();
+                GoodsSku::whereIn('goods_sku_id', $skusOldIds)->update(['goods_sku_status' => 'DISABLED']);
+            }
+
+            Db::commit();
+        } catch (\Exception $e) {
+            dump($e->getTrace());
+            Db::rollBack();
+
+            throw new BusinessException('规格数据更新异常~');
+        }
+    }
+
+    /**
+     * @Desc
+     * @Author Gorden
+     * @Date 2024/3/12 8:45
+     *
+     * @param array $data
+     * @param $model
+     * @return array
+     * @throws BusinessException
+     */
+    private static function inputFilter(array $data, $model): array
+    {
+        $table = config('database.connections.mysql.prefix') . $model->getTable();
+        $allow_column = $model->getConnection()->select("desc `$table`");
+        if (!$allow_column) {
+            throw new BusinessException('表不存在', 2);
+        }
+        $columns = array_column($allow_column, 'Type', 'Field');
+        foreach ($data as $col => $item) {
+            if (!isset($columns[$col])) {
+                unset($data[$col]);
+                continue;
+            }
+            // 非字符串类型传空则为null
+            if ($item === '' && strpos(strtolower($columns[$col]), 'varchar') === false && strpos(strtolower($columns[$col]), 'text') === false) {
+                $data[$col] = null;
+            }
+            if (is_array($item)) {
+                $data[$col] = implode(',', $item);
+            }
+            if ($item != '' && (strpos(strtolower($columns[$col]), 'varchar') || strpos(strtolower($columns[$col]), 'text'))) {
+//                $data[$col] = htmlspecialchars($item);
+            }
+        }
+        if (empty($data['created_at'])) {
+            unset($data['created_at']);
+        }
+        if (empty($data['updated_at'])) {
+            unset($data['updated_at']);
+        }
+        return $data;
+    }
+
+    /**
+     * @Desc 执行更新
+     * @Author Gorden
+     * @Date 2024/3/12 8:43
+     *
+     * @param $id
+     * @param $data
+     * @param $model
+     * @return void
+     */
+    private static function doUpdate($id, $data, $model)
+    {
+        $row = $model->find($id);
+        foreach ($data as $key => $val) {
+            $row->{$key} = $val;
+        }
+        $row->save();
+    }
+
+    /**
+     * @Desc 上架定时
+     * @Author Gorden
+     * @Date 2024/4/11 15:13
+     *
+     * @return void
+     */
+    public static function checkListing()
+    {
+        $key = Goods::LISTING_KEY_PREFIX . date('YmdHi');
+        $redis = Redis::connection();
+        if (!$redis->exists($key)) {
+            return;
+        }
+
+        $goodsIds = $redis->sMembers($key);
+        if (Goods::whereIn('goods_id', $goodsIds)->update(['goods_status' => 'ON'])) {
+            $redis->del($key);
+        }
+    }
+
+    /**
+     * @Desc 自动下架
+     * @Author Gorden
+     * @Date 2024/4/26 15:26
+     *
+     * @return void
+     */
+    public static function checkOffListing()
+    {
+        $key = Goods::LISTING_OFF_KEY_PREFIX . date('YmdHi');
+        $redis = Redis::connection();
+        if (!$redis->exists($key)) {
+            return;
+        }
+
+        $goodsIds = $redis->sMembers($key);
+        if (Goods::whereIn('goods_id', $goodsIds)->update(['goods_status' => 'OFF'])) {
+            $redis->del($key);
+        }
+    }
+
+    public static $week = [
+        '周一' => 1,
+        '周二' => 2,
+        '周三' => 3,
+        '周四' => 4,
+        '周五' => 5,
+        '周六' => 6,
+        '周日' => 7,
+    ];
+}

+ 164 - 44
app/admin/service/notify/RechargeService.php

@@ -2,7 +2,11 @@
 
 namespace app\admin\service\notify;
 
+use app\admin\service\coupon\CouponDetailService;
+use app\model\Coupon;
+use app\model\CouponDetail;
 use app\model\Goods;
+use app\model\Member;
 use app\model\MemberAccount;
 use app\model\MemberQuota;
 use app\model\MemberRole;
@@ -13,6 +17,7 @@ use app\model\RuleAdded;
 use app\model\RuleAddedComponent;
 use Monolog\Handler\IFTTTHandler;
 use support\exception\BusinessException;
+use support\Log;
 
 class RechargeService
 {
@@ -33,7 +38,7 @@ class RechargeService
         }
         $goods = Goods::find($orderSheet->join_sheet_goods_id);
         // 自定义充值产品
-        if($goods->join_goods_category_id == 210){
+        if ($goods->join_goods_category_id == 210) {
             return 0;
         }
         if (empty($goods->goods_attribute_json)) {
@@ -47,6 +52,27 @@ class RechargeService
         return $attributeJson['added']['nbr'];
     }
 
+    public static function getGoodsAttributeJson($orderId)
+    {
+        try {
+            $orderSheet = OrderSheet::where('join_sheet_order_id', $orderId)->first();
+            if (!$orderSheet) {
+                throw new BusinessException('订单数据异常');
+            }
+            $goods = Goods::find($orderSheet->join_sheet_goods_id);
+            if (empty($goods->goods_attribute_json)) {
+                throw new BusinessException('产品数据异常');
+            }
+
+            return json_decode($goods->goods_attribute_json, true);
+
+        } catch (BusinessException $e) {
+            throw new BusinessException($e->getMessage());
+        } catch (\Exception $e) {
+            throw new BusinessException('产品数据异常');
+        }
+    }
+
     /**
      * @Desc
      * @Author Gorden
@@ -54,58 +80,117 @@ class RechargeService
      *
      * @param $memberId
      * @param $payAmount
-     * @return false|mixed
      * @throws BusinessException
      */
     public static function disposeRole($memberId, $payAmount)
     {
-        $memberAccount = MemberAccount::where('member_account_classify', 'CASH')
-            ->where('join_account_member_id', $memberId)
-            ->first();
-        if (!$memberAccount) {
-            throw new BusinessException('账户异常');
+        try {
+            $member = Member::with([
+                'role' => function ($query) {
+                    $query->select('member_role_id', 'member_role_sort');
+                }
+            ])->where('member_id', $memberId)
+                ->first();
+            $memberRoleConfigJson = [];
+            if (!empty($member->member_role_config_json)) {
+                $memberRoleConfigJson = json_decode($member->member_role_config_json, true);
+            }
+            $role = MemberRole::where('member_role_category', 'COMBINE')
+                ->where('member_role_range_begin', '<=', $payAmount)
+                ->where('member_role_range_end', '>=', $payAmount)
+                ->first();
+            $memberRoleId = '';
+            $memberRoleBegintime = '';
+            dump($member->role,$role);
+            // 没有角色,或者有角色,新角色等级高
+            if ((!empty($member->role) && !empty($role) && $role->member_role_sort > $member->role->member_role_sort) || (empty($member->role) && !empty($role))) {
+                $memberRoleId = $role->member_role_id;
+                $memberRoleBegintime = date('Y-m-d H:i:s');
+                $memberRoleConfigJson['next'] = [];
+            } elseif (!empty($member->role) && !empty($role) && $role->member_role_sort == $member->role->member_role_sort) {
+                $memberRoleId = $role->member_role_id;
+                $memberRoleBegintime = date('Y-m-d H:i:s');
+                $memberRoleConfigJson['next'] = [];
+            } elseif (!empty($member->role) && !empty($role) && $role->member_role_sort < $member->role->member_role_sort) {
+                $memberRoleId = $member->role->member_role_id;
+                $memberRoleBegintime = $member->member_role_begintime;
+                $memberRoleConfigJson['next'][] = ['member_role_begintime' => date('Y-m-d H:i:s'), 'member_role_id' => $role->member_role_id];
+            }
+
+            Member::where('member_id', $memberId)->update([
+                'join_member_role_id' => $memberRoleId,
+                'member_role_begintime' => $memberRoleBegintime,
+                'member_role_config_json' => json_encode($memberRoleConfigJson)
+            ]);
+
+        } catch (\Exception $e) {
+            Log::error('计算等级异常:' . $e->getMessage());
+            throw new BusinessException("计算等级异常");
         }
-//        $income = floatval($memberAccount->member_account_income);
-//        $expend = floatval($memberAccount->member_account_expend);
-//        $money = max($income, $expend);
+    }
 
-        $recharge = PayDetail::where('join_pay_member_id',$memberId)
-            ->where('pay_category','RECHARGE')
-            ->where('pay_status','SUCCESS')
-            ->where(function($query){
-                $query->whereIn('pay_prepayid', ['ALIPAY', 'WXPAY','OFFLINE_WXPAY','OFFLINE_ALIPAY','MONEY'])
-                    ->orWhere('pay_prepayid', 'like', '%CASH%');
-            })
-            ->sum('pay_amount');
-//        $expend = PayDetail::where('join_pay_member_id',$memberId)
-//            ->whereIn('pay_category',['GOODS','SERVICE','CHNMED','CHNNCD','PACKAGE','MEALS'])
-//            ->where('pay_status','SUCCESS')
-//            ->whereIn('pay_prepayid', ['ALIPAY', 'WXPAY','OFFLINE_WXPAY','OFFLINE_ALIPAY','MONEY'])
-//            ->sum('pay_amount');
-        $paySuccessDetail = PayDetail::where('join_pay_member_id',$memberId)
-            ->where('pay_status','SUCCESS')
-            ->whereIn('pay_category',['GOODS','SERVICE','CHNMED','CHNNCD','PACKAGE','MEALS'])
-            ->whereIn('pay_prepayid', ['ALIPAY', 'WXPAY','OFFLINE_WXPAY','OFFLINE_ALIPAY','MONEY']);
-        $payAmount = $paySuccessDetail->sum('pay_amount');
-        $paySuccessDetail = $paySuccessDetail->select('pay_id','join_pay_order_id','pay_amount')
-            ->get()
-            ->toArray();
-        $orderIds = array_column($paySuccessDetail,'join_pay_order_id');
-        $refundAmount = PayDetail::whereIn('join_pay_order_id',$orderIds)
-            ->where('pay_category','REFUND')
-            ->where('pay_status','SUCCESS')
-            ->sum('pay_amount');
-        $amount = $payAmount - $refundAmount;
+    public static function disposeRoleCoupon($goodsAttributeJson, $memberId)
+    {
+        try {
+            if (empty($goodsAttributeJson['coupon'])) {
+                return;
+            }
+
+            // 发券
+            foreach ($goodsAttributeJson['coupon'] as $key => $coupon) {
+                $couponModel = Coupon::where('coupon_id', $key)->select('coupon_id', 'coupon_validdate_day', 'coupon_validdate_end', 'coupon_is_period', 'coupon_number')->first();
+                if (empty($couponModel)) {
+                    continue;
+                }
+                // 券是否过期
+                if (!empty($couponModel->coupon_validdate_end) && strtotime($couponModel->coupon_validdate_end) < time()) {
+                    continue;
+                }
+                // 发周期券
+                if ($couponModel->coupon_is_period == 'Y') {
+                    // 发券参数
+                    $couponSendParams = ['gettype' => 'ROLE', 'coupon_id' => $key, 'member_id' => $memberId];
+                    Log::info("发周期券参数", $couponSendParams);
+                    CouponDetailService::sendPeriodCoupon($couponSendParams);
+                    continue;
+                }
+                $couponResidue = 'all';
+                if ($couponModel->coupon_number != 0) {
+                    $couponResidue = CouponDetail::where('join_detail_coupon_id', $key)->whereIn('coupon_detail_status', ['INIT', 'PENDING'])->count();
+                    // 超出优惠券设置的数量
+                    if ($couponResidue < $coupon['num']) {
+                        continue;
+                    }
+                }
+                $endDate = '';
+                if (!empty($couponModel->coupon_validdate_end)) {
+                    $endDate = $couponModel->coupon_validdate_end;
+                } elseif ($couponModel->coupon_validdate_day > 0) {
+                    $endDate = date('Y-m-d H:i:s', time() + ($couponModel->coupon_validdate_day * 24 * 3600) - 1);
+                }
+                // 发券参数
+                $couponSendParams = [
+                    'gettype' => 'ROLE',
+                    'coupon_id' => $key,
+                    'chooseCouponNbr' => $coupon['num'],
+                    'member_id' => $memberId,
+                    'coupon_detail_gain_datetime' => date('Y-m-d H:i:s'),
+                    'coupon_detail_deadline_datetime' => $endDate,
+                ];
 
-        $money = max($recharge, $amount);
-        $memberRole = MemberRole::where('member_role_range_begin' ,'<=',$money)
-            ->where('member_role_range_end','>',$money)
-            ->first();
-        if (!empty($memberRole->member_role_id)){
-            return $memberRole->member_role_id;
+                Log::info("发普通券参数", $couponSendParams);
+                if ($couponResidue != 'all' && $couponResidue - $coupon['num'] >= 0) {
+                    CouponDetailService::customSendCouponHave($couponSendParams);
+                } else {
+                    for ($i = 0; $i < $coupon['num']; $i++) {
+                        CouponDetailService::customSendCoupon($couponSendParams);
+                    }
+                }
+            }
+        } catch (\Exception $e) {
+            throw new BusinessException("发券异常");
         }
 
-        return false;
     }
 
     /**
@@ -257,4 +342,39 @@ class RechargeService
         $model->member_quota_addtimes = time();
         $model->save();
     }
+
+    /**
+     * @Desc 充值前保存原账户数据
+     * @Author Gorden
+     * @Date 2024/10/14 9:18
+     *
+     * @param MemberAccount $memberAccount
+     * @param $payAmount
+     * @param $addedRate
+     * @param $addedAmount
+     * @return void
+     * @throws BusinessException
+     */
+    public static function saveOriginData(MemberAccount $memberAccount, $payAmount, $addedRate, $addedAmount)
+    {
+        try {
+            $memberAccount = $memberAccount->toArray();
+            $memberAccount['pay_amount'] = $payAmount;
+            $memberAccount['added_rate'] = $addedRate;
+            $memberAccount['added_amount'] = $addedAmount;
+
+
+            $member = Member::where('member_id', $memberAccount['join_account_member_id'])->first();
+            $memberExtendJson = [];
+            if (!empty($member->member_extend_json)) {
+                $memberExtendJson = json_decode($member->member_extend_json, true);
+            }
+            $memberExtendJson['snap'][date('Y-m-d H:i:s')] = $memberAccount;
+            $member->member_extend_json = json_encode($memberExtendJson);
+            $member->save();
+
+        } catch (\Exception $e) {
+            throw new BusinessException('存储原数据失败');
+        }
+    }
 }

+ 2 - 2
app/command/WelfareAccountCommand.php

@@ -34,7 +34,7 @@ class WelfareAccountCommand extends Command
         try{
             
             foreach($accounts as $account){
-                if ($account['member_account_income'] == '0.00'){
+                if ($account['member_account_income'] == '0.00' || $account['member_account_surplus'] == '0.00'){
                     echo "会员【" . $account['join_account_member_id'] . "】跳过\n";
                     continue;
                 }
@@ -55,8 +55,8 @@ class WelfareAccountCommand extends Command
             dump($e->getMessage());
 
             Db::rollBack();
+            return self::SUCCESS;
         }
-
     }
 
     /**

+ 28 - 7
route/admin.php

@@ -135,6 +135,15 @@ Route::group('/admin', function () {
         })->middleware([
             \app\middleware\AdminAuthCheck::class
         ]);
+        /* 会员充值权益 */
+        Route::group('/memberRechargeBenefit', function () {
+            Route::get('/list', [\app\admin\controller\goods\MemberRechargeBenefitController::class, 'select']);
+            Route::get('/selectCascaderList', [\app\admin\controller\goods\MemberRechargeBenefitController::class, 'selectCascaderList']);
+            Route::get('/info', [\app\admin\controller\goods\MemberRechargeBenefitController::class, 'info']);
+            Route::post('/update', [\app\admin\controller\goods\MemberRechargeBenefitController::class, 'update']);
+        })->middleware([
+            \app\middleware\AdminAuthCheck::class
+        ]);
     });
     /* 财务管理 */
     Route::group('/finance', function () {
@@ -167,7 +176,7 @@ Route::group('/admin', function () {
         Route::group('/withdrawalList', function () {
             Route::get('/list', [\app\admin\controller\finance\WithdrawalListController::class, 'select']);
             Route::get('/info', [\app\admin\controller\finance\WithdrawalListController::class, 'info']);
-            Route::post('/changeStatus', [\app\admin\controller\finance\WithdrawalListController::class,'changeStatus']);
+            Route::post('/changeStatus', [\app\admin\controller\finance\WithdrawalListController::class, 'changeStatus']);
         })->middleware([
             \app\middleware\AdminAuthCheck::class
         ]);
@@ -302,11 +311,11 @@ Route::group('/admin', function () {
             Route::get('/paramsList', [\app\admin\controller\sys_manage\ConfigController::class, 'paramsList']);
             Route::post('/paramsSave', [\app\admin\controller\sys_manage\ConfigController::class, 'paramsSave']);
 
-            Route::get('/partnerParams',[\app\admin\controller\sys_manage\ConfigController::class,'partnerParamsInfo']);
-            Route::post('/setPartnerParams',[\app\admin\controller\sys_manage\ConfigController::class,'setPartnerParams']);
+            Route::get('/partnerParams', [\app\admin\controller\sys_manage\ConfigController::class, 'partnerParamsInfo']);
+            Route::post('/setPartnerParams', [\app\admin\controller\sys_manage\ConfigController::class, 'setPartnerParams']);
 
-            Route::get('/referrerParams',[\app\admin\controller\sys_manage\ConfigController::class,'referrerParamsInfo']);
-            Route::post('/setReferrerParams',[\app\admin\controller\sys_manage\ConfigController::class,'setReferrerParams']);
+            Route::get('/referrerParams', [\app\admin\controller\sys_manage\ConfigController::class, 'referrerParamsInfo']);
+            Route::post('/setReferrerParams', [\app\admin\controller\sys_manage\ConfigController::class, 'setReferrerParams']);
         });
         /* 运费模板管理 */
         Route::group('/postageTemplate', function () {
@@ -948,8 +957,8 @@ Route::group('/admin', function () {
             Route::post('/update', [\app\admin\controller\coupon\CouponPacketController::class, 'update']);
             Route::get('/info', [\app\admin\controller\coupon\CouponPacketController::class, 'info']);
             Route::delete('/delete', [\app\admin\controller\coupon\CouponPacketController::class, 'delete']);
-            Route::post('/packetIssue',[\app\admin\controller\coupon\CouponPacketController::class,'packetIssue']);
-            Route::post('/packetReIssue',[\app\admin\controller\coupon\CouponPacketController::class,'packetReIssue']);
+            Route::post('/packetIssue', [\app\admin\controller\coupon\CouponPacketController::class, 'packetIssue']);
+            Route::post('/packetReIssue', [\app\admin\controller\coupon\CouponPacketController::class, 'packetReIssue']);
         })->middleware([
             \app\middleware\AdminAuthCheck::class
         ]);
@@ -1137,6 +1146,18 @@ Route::group('/admin', function () {
             Route::post('/insertRechargeWelfare', [\app\admin\controller\order\PayDetailController::class, 'insertRechargeWelfare']);
 //            Route::get('/info', [\app\admin\controller\order\AppointmentController::class, 'info']);
         });
+        // 充值订单
+        Route::group('/recharge', function () {
+            Route::get('/list', [\app\admin\controller\order\RechargeController::class, 'select']);
+            Route::post('/add', [\app\admin\controller\order\RechargeController::class, 'insert']);
+            Route::post('/pay', [\app\admin\controller\order\RechargeController::class, 'pay']);
+            Route::get('/sheet', [\app\admin\controller\order\RechargeController::class, 'sheet']);
+            Route::get('/getPaidOrder', [\app\admin\controller\order\RechargeController::class, 'getPaidOrder']);
+            Route::post('/uploadTicket', [\app\admin\controller\order\RechargeController::class, 'uploadTicket']);
+            Route::get('/getOrderPayStatus', [\app\admin\controller\order\RechargeController::class, 'getOrderPayStatus']);
+        })->middleware([
+            \app\middleware\AdminAuthCheck::class
+        ]);
     });
     /* 统计 */
     Route::group('/statistics', function () {