OrderOper.php 28.8 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857
<?php

namespace addons\groupon\library\traits\model\order;

use addons\groupon\exception\Exception;
use addons\groupon\model\ActivityGoodsSkuPrice;
use addons\groupon\model\Cart;
use addons\groupon\model\Config;
use addons\groupon\model\Coupons;
use addons\groupon\model\User;
use addons\groupon\model\ScoreGoodsSkuPrice;
use addons\groupon\model\Goods;
use addons\groupon\model\UserAddress;
use addons\groupon\model\Dispatch;
use addons\groupon\model\GoodsComment;
use addons\groupon\model\GoodsSkuPrice;
use addons\groupon\model\UserCoupons;
use addons\groupon\model\Order;
use addons\groupon\model\OrderAction;
use addons\groupon\model\OrderItem;
use addons\groupon\model\ActivityGroupon;
use addons\groupon\model\Store;
use addons\groupon\model\Verify;
use app\admin\model\groupon\order\RefundLog;
use think\Cache;
use think\Db;

trait OrderOper
{
    use OrderOperSendGet, OrderOperCreate;

    // 获取订单号
    public static function getSn($user_id)
    {
        $rand = $user_id < 9999 ? mt_rand(100000, 99999999) : mt_rand(100, 99999);
        $order_sn = date('Yhis') . $rand;

        $id = str_pad($user_id, (24 - strlen($order_sn)), '0', STR_PAD_BOTH);

        return $order_sn . $id;
    }


    public static function getRemind()
    {
        $orders = self::with(['user', 'item'])->where('createtime', '>', (time() - (7 * 86400)))->limit(20)->order('id', 'desc')->select();

        $reminds = [];
        foreach ($orders as $key => $order) {
            $user = $order->user;
            $items = $order->item;
            $reminds[] = [
                'avatar' => $user['avatar'] ?? '',
                'remind' => mb_substr($user['nickname'], 0, 2) . '**下单' . count($items) . '件商品'
            ];
        }

        return $reminds;
    }


    // 计算订单
    public static function pre($params, $calc_type = 'pre')
    {
        $user = User::info();

        // 检测必要系统环境
        checkEnv(['bcmath', 'queue']);

        // 获取请求参数 "store_id"
        extract(self::preParams($params));

        // 检测并重新组装要购买的商品列表
        list(
            $new_goods_list,            // 组合好的新的商品列表
            $activity_discounts,        // 订单可能参与的所有活动
            $activity_type              // 商品参与的活动
        ) = self::preCheck($params, $calc_type);

        // 计算订单商品价格,所需积分,运费
        list(
            $new_goods_list,            // 新的商品列表
            $goods_original_amount,     // 商品原始总价
            $goods_amount,              // 商品现在总价
        ) = self::preCalcAmount($params, $new_goods_list);

        // 计算订单优惠折扣,优惠券,邮费
        list(
            $new_goods_list,                // 重新赋值活动, 商品上增加了 activity_type
            $activity_discount_infos,       // 每个活动包含的优惠信息
            $activity_discount_money,       // 促销活动优惠总金额
            $activity_gift_money,           // 赠送的金额
            $activity_gift_coupon_ids,      // 赠送的优惠券 ids
            $activity_type,                 // 全部参与的活动类型
            $user_coupons,                  // 使用的优惠券信息
            $coupon_money                   // 优惠券优惠金额
        ) = self::preCalcDiscount(
            $params,
            $new_goods_list,
            $activity_type,
            $activity_discounts,
            $goods_amount
        );

        // 计算订单总金额,需支付金额
        list(
            $new_goods_list,
            $total_amount,
            $discount_fee,
            $total_fee,
            $coupon_fee,
        ) = self::preCalcOrder(
            $new_goods_list,
            $goods_amount,
            $activity_discount_infos,
            $activity_discount_money,
            $coupon_money
        );

        // 处理返回结果
        return self::preReturnParams(
            $goods_original_amount,
            $goods_amount,
            $total_amount,
            $total_fee,
            $discount_fee,
            $coupon_fee,
            $activity_discount_money,
            $activity_gift_money,
            $activity_gift_coupon_ids,
            $activity_type,
            $new_goods_list,
            $activity_discount_infos,
            $user_coupons,
            $calc_type
        );
    }


    // 获取可用优惠券列表
    public static function coupons($params, $goods_amount = 0)
    {
        $user = User::info();
        extract($params);

        // 商品总金额
        if (!$goods_amount) {
            // 下单的时候把计算好的 goods_amount 传进来了,接口直接获取可用列表的时候,需要计算
            foreach ($goods_list as $k => $goods) {
                $goods_amount += ($goods['goods_price'] * $goods['goods_num']);
            }
        }

        $coupons = Coupons::getCouponsList(Coupons::COUPONS_CAN_USE);

        $new_coupons = [];
        // 过滤,如果有一个产品不适用,则优惠券不允许使用,不显示
        foreach ($coupons as $key => $coupon) {
            if ($coupon['goods_ids'] === '0') {
                // 所有商品可用
                $can_use = true;
            } else {
                $goods_ids = explode(',', $coupon['goods_ids']);

                $can_use = true;
                foreach ($goods_list as $k => $goods) {
                    if (!in_array($goods['goods_id'], $goods_ids)) {
                        $can_use = false;
                        break;
                    }
                }
            }

            // 商品可用 并且 商品金额满足
            if ($can_use && $coupon->enough <= $goods_amount) {
                $new_coupons[] = $coupon;
            }
        }

        $new_coupons = array_values($new_coupons);

        return $new_coupons;
    }


    public static function createOrder($params)
    {
        $user = User::info();

        // 入参
        extract($params);
        $remark = $remark ?? null;
        $store_id = $store_id ?? 0;

        // 订单计算数据
        extract(self::pre($params, "create"));

        $order = Db::transaction(function () use (
            $user,
            $goods_original_amount,
            $goods_amount,
            $total_amount,
            $total_fee,
            $discount_fee,
            $coupon_fee,
            $activity_discount_money,
            $activity_gift_money,
            $activity_gift_coupon_ids,
            $activity_discount_infos,
            $new_goods_list,
            $user_coupons,
            $phone,
            $consignee,
            $store_id,
            $remark,
            $from
        ) {
            // 订单创建前
            $data = [
                'user' => $user,
                'goods_original_amount' => $goods_original_amount,
                'goods_amount' => $goods_amount,
                'total_amount' => $total_amount,
                'total_fee' => $total_fee,
                'discount_fee' => $discount_fee,
                'coupon_fee' => $coupon_fee,
                'activity_discount_money' => $activity_discount_money,
                'activity_gift_money' => $activity_gift_money,
                'activity_gift_coupon_ids' => $activity_gift_coupon_ids,
                'activity_discount_infos' => $activity_discount_infos,
                'new_goods_list' => $new_goods_list,
                'user_coupons' => $user_coupons,
                'remark' => $remark,
                'from' => $from
            ];
            // 这里减掉库存,并判断限购
            \think\Hook::listen('groupon_order_create_before', $data);

            $orderData = [];
            $orderData['order_sn'] = self::getSn($user->id);
            $orderData['user_id'] = $user->id;
            $orderData['goods_amount'] = $goods_amount;
            $orderData['total_amount'] = $total_amount;
            $orderData['total_fee'] = $total_fee;
            $orderData['discount_fee'] = $discount_fee;
            $orderData['coupon_fee'] = $coupon_fee;
            $orderData['activity_discount_money'] = $activity_discount_money;
            $orderData['activity_gift_money'] = $activity_gift_money;       // 满额赠送金额
            $orderData['goods_original_amount'] = $goods_original_amount;
            $orderData['phone'] = $phone;
            $orderData['consignee'] = $consignee;
            $orderData['store_id'] = $store_id;
            $orderData['status'] = 0;
            $orderData['remark'] = $remark;
            $orderData['coupons_id'] = $user_coupons ? $user_coupons->id : 0;
            $orderData['platform'] = request()->header('platform');
            $orderData['pay_fee'] = 0;          // 回调填充
            // $orderData['transaction_id'] = transaction_id;
            // $orderData['payment_json'] = payment_json;
            // $orderData['pay_type'] = pay_type;
            // $orderData['paytime'] = paytime;
            $ext = $activity_discount_infos ? ['activity_discount_infos' => $activity_discount_infos] : [];       // 促销活动信息
            $ext['activity_gift_coupon_ids'] = $activity_gift_coupon_ids;
            $orderData['ext'] = json_encode($ext);
            $order = new Order();
            $order->allowField(true)->save($orderData);

            // 将优惠券使用掉
            if ($user_coupons) {
                $user_coupons->use_order_id = $order->id;
                $user_coupons->usetime = time();
                $user_coupons->save();
            }

            // 添加 订单 item
            foreach ($new_goods_list as $key => $buyinfo) {
                $detail = $buyinfo['detail'];
                $current_sku_price = $detail['current_sku_price'];

                $orderItem = new OrderItem();

                $orderItem->user_id = $user->id;
                $orderItem->order_id = $order->id;
                $orderItem->goods_id = $buyinfo['goods_id'];
                $orderItem->goods_type = $detail['type'];
                $orderItem->goods_sku_price_id = $buyinfo['sku_price_id'];

                $item_activity_type = $detail['activity_status'] == 'ing' ? 'time_sale' : '';
                $item_activity_type .= $buyinfo['activity_type'] ? ',' . $buyinfo['activity_type'] : '';
                $item_activity_type = trim($item_activity_type, ',');

                $orderItem->activity_type = $item_activity_type;     // 商品当前的活动类型
                $orderItem->goods_sku_text = $current_sku_price['goods_sku_text'];
                $orderItem->goods_title = $detail->title;
                $orderItem->goods_image = empty($current_sku_price['image']) ? $detail->image : $current_sku_price['image'];
                $orderItem->goods_original_price = $detail->original_price;
                $orderItem->discount_fee = $buyinfo['discount_fee'];        // 平均计算单件商品所享受的折扣
                $orderItem->pay_price = $buyinfo['pay_price'];        // 平均计算单件商品不算运费,算折扣时候的金额
                $orderItem->goods_price = $detail->current_sku_price->price;
                $orderItem->goods_num = $buyinfo['goods_num'] ?? 1;
                $orderItem->dispatch_status = 0;
                $orderItem->dispatch_type = $buyinfo['dispatch_type'];
                $orderItem->store_id = $buyinfo['store_id'] ? $buyinfo['store_id'] : 0;
                $orderItem->comment_status = 0;
                $orderItem->refund_status = 0;

                $ext = [];
                $orderItem->ext = json_encode($ext);
                $orderItem->save();
            }

            // 订单创建后
            $data = [
                'user' => $user,
                'order' => $order,
                'from' => $from,
                'new_goods_list' => $new_goods_list
            ];
            \think\Hook::listen('groupon_order_create_after', $data);

            // 重新获取订单
            $order = self::where('id', $order['id'])->find();

            return $order;
        });

        return $order;
    }


    // 订单列表
    public static function getList($params)
    {
        $user = User::info();
        extract($params);

        $order = (new self())->where('user_id', $user->id)->with('item');

        switch ($type) {
            case 'all':
                $order = $order;
                break;
            case 'nopay':
                $order = $order->nopay();
                break;
            case 'nosend':
                $order = $order->payed()->nosend(false);     // 默认只查询未备货的订单,参数 false,标示,查询未备货和已备货但是未到货门店的
                break;
            case 'noarrive':
                $order = $order->payed()->noarrive();
                break;
            case 'noget':
                $order = $order->payed()->noget(true);      // 默认查询已备货但是未到货门店的订单,参数 true,标示,只查询已到货门店未提货的
                break;
            case 'nocomment':
                $order = $order->payed()->nocomment();
                break;
            case 'aftersale':
                $order = $order->payed()->aftersale();
                break;
        }

        $orders = $order->order('id', 'desc')->paginate(10);

        // 处理未支付订单 item status_code
        $orders = $orders->toArray();
        if ($orders['data']) {
            $data = $orders['data'];
            foreach ($data as $key => $od) {
                $data[$key] = self::setOrderItemStatusByOrder($od);
            }

            $orders['data'] = $data;
        }

        return $orders;
    }


    // 订单详情
    public static function detail($params)
    {
        $user = User::info();
        extract($params);

        $order = (new self())->with(['item', 'store'])->where('user_id', $user->id);

        if (isset($order_sn)) {
            $order = $order->where('order_sn', $order_sn);
        }
        if (isset($id)) {
            $order = $order->where('id', $id);
        }

        $order = $order->find();

        if (!$order) {
            throw new Exception('订单不存在');
        }

        $is_verify = false;
        if ($order['status'] > 0) {             // 已支付
            foreach ($order['item'] as $item) {
                if (
                    in_array($item['dispatch_status'], [OrderItem::DISPATCH_STATUS_READY, OrderItem::DISPATCH_STATUS_ARRIVE])
                    && $item['refund_status'] <= 0
                ) {
                    // 只要有一个已发货的并且未退款的,就生成总码
                    $is_verify = true;
                }
            }
        }

        if ($is_verify) {
            $order->verify = $order->verify;
        } else {
            $order->verify = [];
        }

        // 处理未支付订单 item status_code
        $order = self::setOrderItemStatusByOrder($order);

        return $order;
    }


    // 订单商品详情
    public static function itemDetail($params)
    {
        $user = User::info();
        extract($params);
        $type = $type ?? 'default';

        $order = (new self())->with(['item' => function ($query) use ($order_item_id) {
            $query->where('id', $order_item_id);
        }])->where('user_id', $user->id);

        if (isset($order_sn)) {
            $order = $order->where('order_sn', $order_sn);
        }
        if (isset($id)) {
            $order = $order->where('id', $id);
        }

        $order = $order->find();

        if (!$order || !$order->item) {
            throw new Exception('订单不存在');
        }

        // 处理未支付订单 item status_code
        $order = self::setOrderItemStatusByOrder($order);
        $item = $order['item'][0];
        unset($order['item']);  // 移除订单表中的 item
        $item['order'] = $order;        // 订单信息

        return $item;
    }


    // 取消订单
    public static function operCancel($params)
    {
        $user = User::info();
        extract($params);

        $order = self::with('item')->where('user_id', $user->id)->where('id', $id)->nopay()->find();

        if (!$order) {
            throw new Exception('订单不存在或已取消');
        }

        // 订单取消
        $order = (new self)->doCancel($order, $user);

        return $order;
    }


    public function doCancel($order, $user, $type = 'user')
    {
        $order = Db::transaction(function () use ($order, $user, $type) {
            $data = ['order' => $order];
            \think\Hook::listen('groupon_order_cancel_before', $data);

            $order->status = Order::STATUS_CANCEL;        // 取消订单
            $order->ext = json_encode($order->setExt($order, ['cancel_time' => time()]));      // 取消时间
            $order->save();

            OrderAction::operAdd($order, null, $user, $type, ($type == 'user' ? '用户' : '管理员') . '取消订单');

            // 订单取消,退回库存,退回优惠券积分,等
            $data = ['order' => $order];
            \think\Hook::listen('groupon_order_cancel_after', $data);

            return $order;
        });

        return $order;
    }


    private static function getItem($order, $order_item_id)
    {
        if (!$order) {
            throw new Exception('当前订单不存在');
        }

        $order_item = null;
        foreach ($order->item as $item) {
            if ($item->id == $order_item_id) {
                $order_item = $item;
                break;
            }
        }

        if (!$order_item) {
            throw new Exception('订单商品不需要操作');
        }

        return $order_item;
    }


    // 确认收货订单
    public static function operConfirm($params)
    {
        $user = User::info();

        $order = Db::transaction(function () use ($params, $user) {
            extract($params);

            $order = self::noget()->with('item')->where('user_id', $user->id)->where('id', $id)->lock(true)->find();

            if (!$order) {
                throw new Exception('订单不需要收货');
            }
            // 循环订单商品,一个一个确认收货,如果已收货跳过
            foreach ($order->item as $item) {
                // 判断并确认收货
                self::operConfirmItemBase($order, $item, false);
            }

            return $order;
        });

        return $order;
    }


    // 确认收货订单商品
    public static function operConfirmItem($params)
    {
        $user = User::info();

        $order = Db::transaction(function () use ($params, $user) {
            extract($params);
            $order = self::noget()->where('user_id', $user->id)->where('id', $id)->lock(true)->find();

            // 获取要操作的 订单 item
            $item = self::getItem($order, $order_item_id);
            // 判断并确认收货
            self::operConfirmItemBase($order, $item);

            return $order;
        });

        return $order;
    }


    private static function operConfirmItemBase($order, $item, $exception = true)
    {
        $user = User::info();

        if ($item->dispatch_status == OrderItem::DISPATCH_STATUS_NOSEND) {
            $exception && new Exception('当前商品未备货');
            return false;
        }
        if ($item->dispatch_status == OrderItem::DISPATCH_STATUS_GETED) {
            $exception && new Exception('当前商品已收货');
            return false;
        }
        if (in_array($item->refund_status, [OrderItem::REFUND_STATUS_OK, OrderItem::REFUND_STATUS_FINISH])) {
            $exception && new Exception('当前商品已退款');
            return false;
        }

        // 查询订单商品所有核销码
        $verifies = Verify::canUse()->where('type', 'verify')
            ->where('user_id', $user->id)
            ->where('order_id', $order['id'])
            ->where('order_item_id', $item['id'])
            ->select();

        foreach ($verifies as $key => $verify) {
            // 是用掉核销码,并且确认收货商品
            (new self())->verifyGeted($order, $item, $verify, ['oper_type' => 'user']);
        }
    }


    // 删除订单
    public static function operDelete($params)
    {
        $user = User::info();
        extract($params);

        $order = self::canDelete()->where('user_id', $user->id)->where('id', $id)->find();

        if (!$order) {
            throw new Exception('订单不存在或不可删除');
        }

        $order = Db::transaction(function () use ($order, $user) {
            $order->delete();        // 删除订单

            OrderAction::operAdd($order, null, $user, 'user', '用户删除订单');

            return $order;
        });

        return $order;
    }


    // 评价
    public static function operComment($params)
    {
        $user = User::info();
        extract($params);

        $order = self::with('item')->payed()->where('user_id', $user->id)->where('id', $id)->find();

        // 获取要操作的 订单 item
        $item = self::getItem($order, $order_item_id);
        if ($item->comment_status == 1) {
            throw new Exception('当前商品已评价');
        }


        $order = Db::transaction(function () use ($order, $item, $user, $params) {
            // 订单评价前
            $data = ['order' => $order, 'item' => $item];
            \think\Hook::listen('groupon_order_comment_before', $data);     // 重新拿到更新过的订单

            extract($params);
            $images = (isset($images) && $images) ? $images : null;

            GoodsComment::create([
                'goods_id' => $item->goods_id,
                'order_id' => $order->id,
                'order_item_id' => $item->id,
                'user_id' => $user->id,
                'level' => $level,
                'content' => $content,
                'images' => $images ? implode(',', $images) : $images,
                'status' => 'show'
            ]);

            $item->comment_status = OrderItem::COMMENT_STATUS_OK;        // 评价成功
            $item->save();

            OrderAction::operAdd($order, $item, $user, 'user', '用户评价成功');

            // 订单评价后
            $data = ['order' => $order, 'item' => $item];
            \think\Hook::listen('groupon_order_comment_after', $data);

            return $order;
        });

        return $order;
    }



    // 个人中心订单数量
    public static function statusNum()
    {
        $user = User::info();

        $status_num['nopay'] = self::where('user_id', $user->id)->nopay()->count();
        $status_num['nosend'] = self::where('user_id', $user->id)->payed()->nosend(false)->count();
        $status_num['noarrive'] = self::where('user_id', $user->id)->payed()->noarrive()->count();
        $status_num['noget'] = self::where('user_id', $user->id)->payed()->noget(true)->count();
        $status_num['nocomment'] = self::where('user_id', $user->id)->payed()->nocomment()->count();

        return $status_num;
    }


    public function paymentProcess($order, $notify)
    {
        $order->status = Order::STATUS_PAYED;
        $order->paytime = time();
        $order->transaction_id = $notify['transaction_id'];
        $order->payment_json = $notify['payment_json'];
        $order->pay_type = $notify['pay_type'];
        $order->pay_fee = $notify['pay_fee'];
        $order->save();

        $user = User::where('id', $order->user_id)->find();
        OrderAction::operAdd($order, null, $user, 'user', '用户支付成功');

        // 支付成功后续使用异步队列处理
        \think\Queue::push('\addons\groupon\job\OrderPayed@payed', ['order' => $order, 'user' => $user], 'groupon-high');
        return $order;
    }


    // 开始退款
    public static function startRefund($order, $item, $refund_money, $user = null, $remark = '')
    {
        // 订单退款前
        $data = ['order' => $order, 'item' => $item];
        \think\Hook::listen('groupon_order_refund_before', $data);

        $item->refund_status = \app\admin\model\groupon\order\OrderItem::REFUND_STATUS_OK;    // 同意退款
        $item->refund_fee = $refund_money;
        $item->save();

        \addons\groupon\model\OrderAction::operAdd($order, $item, $user, ($user ? 'admin' : 'system'), $remark . ',退款金额:' . $refund_money);

        \app\admin\model\groupon\order\Order::refund($order, $item, $refund_money, $remark);

        // 订单退款后
        $data = ['order' => $order, 'item' => $item];
        \think\Hook::listen('groupon_order_refund_after', $data);
    }


    // 退款
    public static function refund($order, $item, $refund_money, $remark = '')
    {
        // 生成退款单
        $refundLog = new RefundLog();
        $refundLog->order_sn = $order->order_sn;
        $refundLog->refund_sn = RefundLog::getSn($order->user_id);
        $refundLog->order_item_id = $item->id;
        $refundLog->pay_fee = $order->pay_fee;
        $refundLog->refund_fee = $refund_money;
        $refundLog->pay_type = $order->pay_type;
        $refundLog->save();

        if ($order->pay_type == 'wechat' || $order->pay_type == 'alipay') {
            // 微信|支付宝退款

            // 退款数据
            $order_data = [
                'out_trade_no' => $order->order_sn
            ];

            if ($order->pay_type == 'wechat') {
                $total_fee = $order->pay_fee * 100;
                $refund_fee = $refund_money * 100;

                $order_data = array_merge($order_data, [
                    'out_refund_no' => $refundLog->refund_sn,
                    'total_fee' => $total_fee,
                    'refund_fee' => $refund_fee,
                    'refund_desc' => $remark,
                ]);
            } else {
                $order_data = array_merge($order_data, [
                    'out_request_no' => $refundLog->refund_sn,
                    'refund_amount' => $refund_money,
                    'refund_reason' => $remark,
                ]);
            }

            $pay_version = pay_version();

            if ($pay_version == 'v3') {
                $pay = new \addons\groupon\library\payv3\PayServiceV3($order->pay_type, $order->platform);
            } else {
                $notify_url = request()->domain() . '/addons/groupon/pay/notifyr/payment/' . $order->pay_type . '/platform/' . $order->platform;

                $pay = new \addons\groupon\library\PayService($order->pay_type, $order->platform, $notify_url);
            }

            $result = $pay->refund($order_data);

            return true;

            // {        // 微信返回结果
            //     "return_code":"SUCCESS",
            //     "return_msg":"OK",
            //     "appid":"wx39cd0799d4567dd0",
            //     "mch_id":"1481069012",
            //     "nonce_str":"huW9eIAb5BDPn0Ma",
            //     "sign":"250316740B263FE53F5DFF50AF5A8FA1",
            //     "result_code":"SUCCESS",
            //     "transaction_id":"4200000497202004072822298902",
            //     "out_trade_no":"202010300857029180027000",
            //     "out_refund_no":"1586241595",
            //     "refund_id":"50300603862020040700031444448",
            //     "refund_channel":[],
            //     "refund_fee":"1",
            //     "coupon_refund_fee":"0",
            //     "total_fee":"1",
            //     "cash_fee":"1",
            //     "coupon_refund_count":"0",
            //     "cash_refund_fee":"1
            // }

            // {        // 支付宝返回结果
            //     "code": "10000",
            //     "msg": "Success",
            //     "buyer_logon_id": "157***@163.com",
            //     "buyer_user_id": "2088902485164146",
            //     "fund_change": "Y",
            //     "gmt_refund_pay": "2020-08-15 16:11:45",
            //     "out_trade_no": "202002460317545607015300",
            //     "refund_fee": "0.01",
            //     "send_back_fee": "0.00",
            //     "trade_no": "2020081522001464141438570535"
            // }
        } else if ($order->pay_type == 'wallet') {
            // 余额退款
            if ($refund_money != 0) {
                \addons\groupon\model\User::money($refund_money, $order->user_id, 'wallet_refund', $order->id, '', [
                    'order_id' => $order->id,
                    'order_sn' => $order->order_sn,
                    'item_id' => $item->id,
                ]);
            }

            self::refundFinish($order, $item, $refundLog);

            return true;
        }
    }

    public static function refundFinish($order, $item, $refundLog)
    {
        // 退款完成
        $refundLog->status = 1;
        $refundLog->save();

        // 退款完成
        $item->refund_status = \app\admin\model\groupon\order\OrderItem::REFUND_STATUS_FINISH;    // 退款完成
        $item->save();
        \addons\groupon\model\OrderAction::operAdd($order, $item, null, 'admin', '退款成功');
    }



    public function setExt($order, $field, $origin = [])
    {
        $newExt = array_merge($origin, $field);

        $orderExt = $order['ext_arr'];

        return array_merge($orderExt, $newExt);
    }
}