<?php
/**
 *  ╔═══════════════════════════════════════════════════╗
 *  ║                                                   ║
 *  ║     ██╗  ██╗   █████╗    ██████╗                  ║
 *  ║     ██║  ██║  ██╔══██╗  ██╔═══██╗                 ║
 *  ║     ███████║  ███████║  ██║   ██║                 ║
 *  ║     ██╔══██║  ██╔══██║  ██║   ██║                 ║
 *  ║     ██║  ██║  ██║  ██║  ╚██████╔╝   SNS           ║
 *  ║                                                   ║    
 *  ║                                                   ║    
 *  ║     © 2023 HaoSNS™ All Rights Reserved            ║
 *  ║     官方网站: https://www.haosns.com                *
 *  ║     本代码由赣州乐易网络科技有限公司®提供             *
 *  ║                                                    *
 *  ║   未经授权禁止复制、传播或用于其他商业目的            *
 *  ║                                                   ║
 *  ╚═══════════════════════════════════════════════════╝
 */


namespace app\api\logic\Order;


use app\common\enum\AfterSaleEnum;
use app\common\enum\AfterSaleLogEnum;
use app\common\enum\DeliveryEnum;
use app\common\enum\GoodsEnum;
use app\common\enum\OrderEnum;
use app\common\enum\OrderLogEnum;
use app\common\enum\PayEnum;
use app\common\enum\YesNoEnum;
use app\common\model\AfterSale;
use app\common\model\AfterSaleGoods;
use app\common\model\Cart;
use app\common\model\Express;
use app\common\model\Goods;
use app\common\model\GoodsItem;
use app\common\model\Order;
use app\common\model\OrderGoods;
use app\common\model\OrderLog;
use app\common\model\Region;
use app\common\model\User;
use app\common\logic\BaseLogic;
use app\common\model\UserAddress;
use app\common\service\after_sale\AfterSaleService;
use app\common\service\ConfigService;
use app\common\service\FileService;
use expressage\Kd100;
use expressage\Kdniao;
use expressage\Kdaliyun;
use think\Exception;
use think\facade\Db;
use think\facade\Validate;

/**
 * 订单逻辑
 * Class OrderLogic
 * @package app\api\logic
 */
class OrderLogic extends BaseLogic
{

    /**
     * 下单用户
     * @var
     */
    protected static $user;

    /**
     * 订单类型
     * @var int
     */
    protected static $OrderType = OrderEnum::NORMAL_ORDER;


    /**
     * 订单数量
     * @var int
     */
    protected static $totalNum = 0;


    /**
     * 订单金额
     * @var array
     */
    protected static $orderPrice = [
        'total_goods_price'     => 0,//订单商品金额
        'express_price'         => 0,//运费
        'total_amount'          => 0,//订单金额
        'order_amount'          => 0,//订单实付金额
        'discount_amount'       => 0,//优惠金额
        'member_amount'         => 0,//会员折扣价
        'total_goods_original_price'  => 0,//订单商品原价总价
    ];



    /**
     * @notes 当前下单用户
     * @param $userId
     * @return array
     */
    public static function setOrderUser($userId)
    {
        self::$user = User::findOrEmpty($userId)->toArray();
        return self::$user;
    }


    /**
     * @notes 订单结算详情
     * @param $params
     * @return array|bool
     */
    public static function settlement($params)
    {
        try {
            //设置订单类型
            self::$OrderType = $params['order_type'];

            //设置用户信息
            $user = self::setOrderUser($params['user_id']);

            //设置用户地址
            $userAddress = UserAddress::getOneAddress($params['user_id'], $params['address_id'] ?? 0);

            //获取商品信息
            $goodsLists = self::getOrderGoodsData($params);

            
            //判断是否需要地址
            $is_address = 1;
           
            //计算运费
            self::$orderPrice['express_price'] = FreightLogic::calculateFreight($goodsLists, $userAddress);
            
            // 订单金额
            self::$orderPrice['total_amount'] += self::$orderPrice['express_price'];

            //订单应付金额
            self::$orderPrice['order_amount'] += self::$orderPrice['express_price'];

            $result = [
                'terminal'              => $params['terminal'],
                'delivery_type'         => intval($params['delivery_type']),
                'delivery_type_desc'    => DeliveryEnum::getDeliveryTypeDesc($params['delivery_type']),
                'cart_id'               => $params['cart_id'] ?? [],
                'order_type'            => self::$OrderType,
                'coupon_list_id'        => intval($params['coupon_list_id'] ?? 0),
                'total_num'             => self::$totalNum,
                'total_goods_price'     => round(self::$orderPrice['total_goods_price'], 2),
                'total_amount'          => round(self::$orderPrice['total_amount'], 2),
                'order_amount'          => round(self::$orderPrice['order_amount'], 2),
                'discount_amount'       => round(self::$orderPrice['discount_amount'], 2),
                'member_amount'         => round(self::$orderPrice['member_amount'],2),
                'express_price'         => round(self::$orderPrice['express_price'], 2),
                'total_goods_original_price'     => round(self::$orderPrice['total_goods_original_price'], 2),
                'user_id'               => $user['id'],
                'user_money'            => $user['user_money'],
                'user_remark'           => $params['user_remark'] ?? '',
                'address'               => $userAddress,
                'goods'                 => $goodsLists,
                'selffetch_shop_id'     => $params['selffetch_shop_id'] ?? '',
                'selffetch_info'        => [],
                'contact'               => $params['contact'] ?? '',
                'mobile'                => $params['mobile'] ?? '',
                'is_address'            => $is_address,
            ];

            return $result;

        } catch (\Exception $e) {
            self::$error = $e->getMessage();
            return false;
        }
    }

    /**
     * @notes 提交订单前验证
     * @param $params
     * @throws \Exception
     */
    public static function submitBeforeCheck($params)
    {
        //配送方式为快递配送时,检测地址
        if (empty($params['address']) && $params['delivery_type'] == DeliveryEnum::EXPRESS_DELIVERY && $params['is_address'] == 1) {
            throw new \Exception('请选择收货地址');
        }

        // 校验商品数量
        foreach ($params['goods'] as $goods) {
            if ($goods['goods_num'] <= 0) {
                throw  new \Exception('请选择商品' . ($goods['goods_name'] ?? '') . '数量');
            }
        }

        //验证订单商品是否支持对应的配送方式
        $is_express = ConfigService::get('delivery_type', 'is_express', 1);
        $item_ids = implode(',', array_column($params['goods'], 'item_id'));
        $goods_ids = implode(',', GoodsItem::where('id', 'in', $item_ids)->column('goods_id'));
        $goods = Goods::where('id', 'in', $goods_ids)->select();
        $goods_name = [];

        //快递配送
        if ($params['delivery_type'] == DeliveryEnum::EXPRESS_DELIVERY) { 
            if ($is_express == 0) {
                throw  new \Exception('系统未开启快递配送方式');
            }

            foreach ($goods as $val) {
                //实物商品且不支持物流
                if ($val['is_express'] == 0 && GoodsEnum::GOODS_REALITY == $val['type']) {
                    $goods_name[] = $val['name'];
                }
            }
        }
        if (!empty($goods_name)) {
            throw new \Exception(implode('、', $goods_name) . '不支持' . DeliveryEnum::getDeliveryTypeDesc($params['delivery_type']) . ',请重新选择配送方式');
        }
    }


    /**
     * @notes 提交订单
     * @param $params
     * @return array|bool
     */
    public static function submitOrder($params)
    {
        Db::startTrans();
        try {
            //提交前验证
            self::submitBeforeCheck($params);

            //删除购物车
            self::delCartByOrder($params);

            //下单扣除库存
            self::decStock($params['goods']);

            //提交订单
            $order = self::addOrder($params, self::$user['id']);

            //下单增加商品销量
            self::incSale($params['goods']);

            //订单日志
            (new OrderLog())->record([
                'type' => OrderLogEnum::TYPE_USER,
                'channel' => OrderLogEnum::USER_ADD_ORDER,
                'order_id' => $order['id'],
                'operator_id' => self::$user['id'],
            ]);

            //提交事务
            Db::commit();
            return ['order_id' => $order['id'], 'type' => 'order'];
        } catch (\Exception $e) {
            Db::rollback();
            self::$error = $e->getMessage();
            return false;
        }
    }


    /**
     * @notes 扣减库存
     * @param $goodLists
     * @throws \Exception
     */
    public static function decStock($goodLists)
    {
        foreach ($goodLists as $goods) {
            $goodsItem = GoodsItem::where(['id' => $goods['item_id']])->findOrEmpty()->toArray();
            if ($goodsItem['stock'] < $goods['goods_num']) {
                throw new \Exception('商品库存不足');
            }
            //更新商品总库存
            Goods::update(['total_stock' => ['dec', $goods['goods_num']]], ['id' => $goods['goods_id']]);
            //更新规格库存
            GoodsItem::update(['stock' => ['dec', $goods['goods_num']]], ['id' => $goods['item_id']]);
        }
    }

    /**
     * @notes 下单增加销量
     * @param $goodLists
     * @throws \Exception
     */
    public static function incSale($goodLists)
    {
        foreach ($goodLists as $goods) {
            Goods::update(['sales_num' => ['inc', $goods['goods_num']]], ['id' => $goods['goods_id']]);
        }
    }


    /**
     * @notes 删除购物车(购物车下单情况)
     * @param $params
     */
    public static function delCartByOrder($params)
    {
        if (!empty($params['cart_id'])) {
            Cart::where(['id' => $params['cart_id'], 'user_id' => self::$user['id']])->delete();
        }
    }


    /**
     * @notes 添加订单
     * @param $params
     * @param $user_id
     */
    public static function addOrder($params, $user_id)
    {
        $order = Order::create([
            'sn'                => generate_sn((new Order()), 'sn'),
            'order_type'        => $params['order_type'],
            'user_id'           => $user_id,
            'order_terminal'    => $params['terminal'],
            'coupon_list_id'    => $params['coupon_list_id'],
            'total_num'         => $params['total_num'],
            'total_amount'      => $params['total_amount'],
            'goods_price'       => $params['total_goods_price'],
            'order_amount'      => $params['order_amount'],
            'express_price'     => $params['express_price'],
            'discount_amount'   => $params['discount_amount'],
            'member_amount'     => $params['member_amount'],
            'user_remark'       => $params['user_remark'],
            'address'       => [
                'contact'       =>  ($params['address']['contact'] ?? ''),
                'province'      =>  ($params['address']['province_id'] ?? ''),
                'city'          =>  ($params['address']['city_id'] ?? ''),
                'district'      =>  ($params['address']['district_id'] ?? ''),
                'address'       =>  ($params['address']['address'] ?? ''),
                'mobile'        =>  ($params['address']['mobile'] ?? ''),
            ],
            'delivery_type'     => $params['delivery_type']
        ]);
        $goodsData = [];
        foreach ($params['goods'] as $goods) {

            //商品实付价格
            $totalPayPrice = $goods['sub_price'] - ($goods['discount_price'] ?? 0);
            $totalPayPrice = $totalPayPrice <= 0 ? 0 : $totalPayPrice;

            $goodsData[] = [
                'order_id'          => $order['id'],
                'goods_id'          => $goods['goods_id'],
                'item_id'           => $goods['item_id'],
                'goods_name'        => $goods['goods_name'],
                'goods_num'         => $goods['goods_num'],
                'goods_price'       => $goods['sell_price'],//商品价格单价(未扣减优惠和积分价格)
                'total_price'       => $goods['sub_price'],
                'total_pay_price'   => $totalPayPrice,//实际支付商品金额(扣除优惠金额)
                'spec_value_ids'    => $goods['spec_value_ids'],
                'discount_price'    => $goods['discount_price'] ?? 0,//优惠券优惠金额
                'original_price'    => $goods['original_price'] ?? 0,//商品原始价格
                'member_price'      => $goods['member_price'] ?? 0,//商品会员价格
                'goods_snap'        => $goods,
            ];
        }
        (new OrderGoods())->saveAll($goodsData);

        return $order;
    }


    /**
     * @notes 商品信息
     * @param $params
     * @return array
     */
    public static function getOrderGoodsData($params)
    {
        // 购物车下单
        if ($params['source'] == 'cart') {
            $params['goods'] = Cart::where([
                ['id', 'in', $params['cart_id']],
                ['user_id', '=', $params['user_id']],
            ])->field('item_id,goods_id,goods_num')->select()->toArray();
        }

        $itemIds = array_column($params['goods'], 'item_id');

        $field = [
            'gi.id' => 'item_id', 'gi.image' => 'item_image',
            'gi.spec_value_str', 'spec_value_ids', 'gi.sell_price',
            'gi.volume', 'gi.stock', 'gi.weight', 'g.id' => 'goods_id',
            'g.name' => 'goods_name', 'g.type', 'g.status', 'g.delete_time', 'g.image',
            'g.express_type', 'g.express_money', 'g.express_template_id',
            'g.is_express', 'g.is_selffetch', 'g.is_express', 'g.is_virtualdelivery',
            'g.after_pay', 'g.after_delivery', 'g.delivery_content', 'g.code', 'g.is_address'
        ];

        $goodsData = (new Goods())->alias('g')
            ->join('goods_item gi', 'gi.goods_id = g.id')
            ->where('gi.id', 'in', $itemIds)
            ->column($field, 'gi.id');

        //处理图片路径
        foreach ($goodsData as &$val) {
            $val['image'] = trim($val['image']) ? FileService::getFileUrl($val['image']) : '';
        }

        
        $goodsLists = self::getOrderGoodsLists($params, $goodsData);
        return $goodsLists;
    }


    /**
     * @notes 结算商品列表
     * @param $goods
     * @param $goodsData
     * @return array
     */
    public static function getOrderGoodsLists($params, $goodsData)
    {
        $goods = $params['goods'];
        $goodsIds = array_column($goodsData, 'goods_id');
        $goodsLists = [];
        foreach ($goods as $k => $item) {
            //删除没找到商品信息的商品
            if (!isset($goodsData[$item['item_id']])) {
                unset($goods[$k]);
                continue;
            }

            //组装商品数据
            $goodsInfo = $goodsData[$item['item_id']];

            //当前商品是否被删除或下架
            if ($goodsInfo['delete_time'] > 0 || $goodsInfo['status'] != 1) {
                throw new \Exception($goodsInfo['goods_name'] . '已下架,请重新选择购买');
            }

            //当前库存是否足够
            if ($item['goods_num'] > $goodsInfo['stock']) {
                throw new \Exception($goodsInfo['goods_name'] . '(' . $goodsInfo['spec_value_str'] . ')' . '库存不足' . $item['goods_num'] . '件，请重新选择购买');
            }
            $goodsInfo['member_price'] = 0;
            //记录原价
            $goodsInfo['original_price'] = $goodsInfo['sell_price'];
            // 获取不同订单类型的规格单价
            $goodsInfo['sell_price'] = self::getSellPrice($params, $goodsInfo);


            $goodsInfo['sub_price'] = round($goodsInfo['sell_price'] * $item['goods_num'], 2);
            $goodsInfo['goods_num'] = intval($item['goods_num']);
            $goodsInfo['total_original_price'] = round($goodsInfo['original_price'] * $goodsInfo['goods_num'], 2);//商品原价合计
            $goodsLists[] = $goodsInfo;

            self::$totalNum += $item['goods_num'];
            self::$orderPrice['total_goods_price'] += $goodsInfo['sub_price'];
            //普通商品，计算折扣金额
            if(in_array(self::$OrderType,[OrderEnum::NORMAL_ORDER])){
                $memberAmount = round(($goodsInfo['original_price'] - $goodsInfo['sell_price']) * $item['goods_num'],2);
                self::$orderPrice['member_amount'] += $memberAmount;
            }
            
            //订单商品原价总价
            self::$orderPrice['total_goods_original_price'] += $goodsInfo['total_original_price'];
        }
        //订单金额
        self::$orderPrice['total_amount'] = self::$orderPrice['total_goods_price'] + self::$orderPrice['member_amount'];
        //订单应付金额
        self::$orderPrice['order_amount'] = self::$orderPrice['total_goods_price'];

        return $goodsLists;
    }


    /**
     * @notes 订单详情
     * @param $params
     * @return array
     */
    public static function getDetail($params)
    {
        $result = (new Order())->with(['order_goods' => function ($query) {
            $query->field([
                'id', 'order_id', 'goods_id', 'item_id', 'goods_snap',
                'goods_name', 'goods_price', 'goods_num', 'total_price', 'total_pay_price'
            ])->append(['goods_image', 'spec_value_str','original_price'])->hidden(['goods_snap']);
        }])
            ->where(['id' => $params['id'], 'user_id' => $params['user_id']])
            ->append(['btn', 'delivery_address', 'cancel_unpaid_orders_time', 'show_pickup_code'])
            ->hidden(['user_id', 'order_terminal', 'transaction_id', 'delete_time', 'update_time'])
            ->findOrEmpty()->toArray();

        //订单类型
        $result['order_type_desc'] =  OrderEnum::getOrderTypeDesc($result['order_type']);

        //订单状态描述
        $result['order_status_desc'] =  OrderEnum::getOrderStatusDesc($result['order_status']);


        //地址  省市区分隔开
        $result['address']['province'] = Region::where('id', $result['address']['province'])->value('name');
        $result['address']['city'] = Region::where('id', $result['address']['city'])->value('name');
        $result['address']['district'] = Region::where('id', $result['address']['district'])->value('name');

        //订单商品原价总价
        $result['total_original_price'] = 0;

        //订单商品售后按钮处理
        foreach ($result['order_goods'] as &$goods) {
            $goods['after_sale_btn'] = 0;//售后按钮关闭
            $after_sale = AfterSale::where(['order_goods_id' => $goods['id'], 'order_id' => $params['id']])->findOrEmpty();
            $after_sale_goods = AfterSaleGoods::where(['order_goods_id' => $goods['id'], 'after_sale_id' => $after_sale['id']])->findOrEmpty();
            $goods['after_sale_id'] = $after_sale_goods['id'] ?? 0;

            if ($result['order_status'] == OrderEnum::STATUS_FINISH && $result['after_sale_deadline'] > time() && $after_sale->isEmpty()) {
                $goods['after_sale_btn'] = 1;//售后按钮开启
            }
            if ($result['order_status'] == OrderEnum::STATUS_FINISH && $result['after_sale_deadline'] > time() && $after_sale['status'] == AfterSaleEnum::STATUS_ING) {
                $goods['after_sale_btn'] = 2;//售后中
            }
            if ($result['order_status'] == OrderEnum::STATUS_FINISH && $result['after_sale_deadline'] > time() && $after_sale['status'] == AfterSaleEnum::STATUS_SUCCESS) {
                $goods['after_sale_btn'] = 3;//售后成功
            }
            if ($result['order_status'] == OrderEnum::STATUS_FINISH && $result['after_sale_deadline'] > time() && $after_sale['status'] == AfterSaleEnum::STATUS_FAIL) {
                $goods['after_sale_btn'] = 4;//售后失败
            }

            $goods['total_original_price'] = $goods['original_price'] * $goods['goods_num'];
            $result['total_original_price'] += $goods['original_price'] * $goods['goods_num'];
        }
        $result['total_original_price'] = round($result['total_original_price'],2);
        //商品详情屏蔽查看内容按钮
        $result['btn']['content_btn'] = OrderEnum::BTN_HIDE;

        // 评论内容
        $result['comment']=\app\common\model\GoodsComment::where('order_goods_id',$params['id'])->find();

        return $result;
    }


    /**
     * @notes 取消订单
     * @param $params
     * @return bool
     */
    public static function cancelOrder($params)
    {
        Db::startTrans();
        try {
            $order = (new Order())->getUserOrderById($params['id'], $params['user_id']);

            //处于已支付状态的发起整单售后
            if ($order['pay_status'] == PayEnum::ISPAID) {
                AfterSaleService::orderRefund([
                    'order_id' => $params['id'],
                    'scene' => AfterSaleLogEnum::BUYER_CANCEL_ORDER
                ]);
            }

            //更新订单为已关闭
            Order::update([
                'order_status' => OrderEnum::STATUS_CLOSE,
                'cancel_time' => time()
            ], ['id' => $order['id']]);

            $returnInventory = ConfigService::get('transaction', 'return_inventory');
            if ($returnInventory) {
                // 需退还库存
                AfterSaleService::returnInventory(['order_id' => $order['id']]);
            }

            //订单日志
            (new OrderLog())->record([
                'type' => OrderLogEnum::TYPE_USER,
                'channel' => OrderLogEnum::USER_CANCEL_ORDER,
                'order_id' => $params['id'],
                'operator_id' => $params['user_id'],
            ]);            

            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::$error = $e->getMessage();
            return false;
        }
    }


    /**
     * @notes 确认订单
     * @param $params
     */
    public static function confirmOrder($params)
    {
        //更新订单状态
        Order::update([
            'order_status' => OrderEnum::STATUS_FINISH,
            'confirm_take_time' => time(),
            'after_sale_deadline' => self::getAfterSaleDeadline(), //售后截止时间
        ], ['id' => $params['id'], 'user_id' => $params['user_id']]);

        //订单日志
        (new OrderLog())->record([
            'type' => OrderLogEnum::TYPE_USER,
            'channel' => OrderLogEnum::USER_CONFIRM_ORDER,
            'order_id' => $params['id'],
            'operator_id' => $params['user_id']
        ]);
    }


    /**
     * @notes 获取当前售后
     * @return float|int
     */
    public static function getAfterSaleDeadline()
    {
        //是否关闭维权
        $afterSale = ConfigService::get('transaction', 'after_sales');
        //可维权时间
        $afterSaleDays = ConfigService::get('transaction', 'after_sales_days');

        if ($afterSale == YesNoEnum::NO) {
            $afterSaleDeadline = time();
        } else {
            $afterSaleDeadline = ($afterSaleDays * 24 * 60 * 60) + time();
        }

        return $afterSaleDeadline;
    }


    /**
     * @notes 查看物流
     * @param $params
     * @return array[]
     */
    public static function orderTraces($params)
    {
        // 获取订单信息,物流信息
        $order = Order::alias('o')
            ->join('order_goods og', 'o.id = og.order_id')
            ->join('goods g', 'og.goods_id = g.id')
            ->join('delivery d', 'd.order_id = o.id')
            ->field('g.image,o.order_status,d.express_name,d.invoice_no,o.total_num,d.contact,d.mobile,o.address,o.confirm_take_time,d.send_type,d.express_id,o.express_time,o.pay_time,o.create_time')
            ->append(['delivery_address'])
            ->where(['o.id' => $params['id'], 'o.user_id' => $params['user_id']])
            ->find()
            ->toArray();

        // 判断是否为快递物流发货, 无物流的不用发货
        $traces = [];
        $shipment = [];
        if ($order['send_type'] == DeliveryEnum::EXPRESS && $order['order_status'] > OrderEnum::STATUS_WAIT_DELIVERY) {

            $shipment = [
                'title' => '已发货',
                'tips' => '商品已出库',
                'time' => $order['express_time'],
            ];

            // 获取物流查询配置, 发起查询申请
            $express_type = ConfigService::get('logistics_config', 'express_type', '');
            $express_bird = unserialize(ConfigService::get('logistics_config', 'express_bird', ''));
            $express_hundred = unserialize(ConfigService::get('logistics_config', 'express_hundred', ''));
            $express_aliyun = unserialize(ConfigService::get('logistics_config', 'express_aliyun', ''));

            if (!empty($express_type) && !empty($express_bird) && !empty($express_hundred)) {

                $express_field = 'code';
                if ($express_type === 'express_bird') {
                    $expressage = (new Kdniao($express_bird['ebussiness_id'], $express_bird['app_key']));
                    $express_field = 'codebird';
                } elseif ($express_type === 'express_hundred') {
                    $expressage = (new Kd100($express_hundred['customer'], $express_hundred['app_key']));
                    $express_field = 'code100';
                } elseif ($express_type === 'express_aliyun') {
                    $expressage = (new \expressage\KdAliyun($express_aliyun['app_code'], $express_aliyun['app_key'],$express_aliyun['app_secret']));
                    $express_field = 'codealiyun';
                }

                //快递编码
                $express_code = Express::where('id', $order['express_id'])->value($express_field);

                //获取物流轨迹
                if ($express_code === 'SF' && $express_type === 'express_bird') {
                    $traces = $expressage->logistics($express_code, $order['invoice_no'], substr($order['address']['mobile'], -4));
                } else {
                    $traces = $expressage->logistics($express_code, $order['invoice_no'], substr($order['address']['mobile'], -4));
                }

                // $traces = $expressage->logisticsFormat();
                if ($traces != false) {
                    foreach ($traces as &$item) {
                        $item = array_values(array_unique($item));
                    }
                }
            }
        }

        // 组装数据返回
        return [
            'order' => [
                'goods_image' => FileService::getFileUrl($order['image']),
                'goods_count' => $order['total_num'],
                'express_name' => $order['express_name'],
                'invoice_no' => $order['invoice_no'],
                'order_status' => $order['order_status'],
                'send_type' => $order['send_type'],
            ],
            'take' => [
                'contact' => $order['contact'],
                'mobile' => $order['mobile'],
                'address' => $order['delivery_address'],
            ],
            'finish' => [
                'title' => '交易完成',
                'tips' => ($order['order_status'] == OrderEnum::STATUS_FINISH) ? '订单交易完成' : '',
                'time' => ($order['order_status'] == OrderEnum::STATUS_FINISH) ? $order['confirm_take_time'] : '',
            ],
            'delivery' => [
                'title' => '运输中',
                'traces' => $traces
            ],
            'shipment' => $shipment,
            'pay' => [
                'title' => '已支付',
                'tips' => '订单支付成功，等待商家发货',
                'time' => $order['pay_time']
            ],
            'buy' => [
                'title' => '已下单',
                'tips' => '订单提交成功',
                'time' => $order['create_time']
            ],
        ];
    }

    /**
     * @notes 获取配送方式
     * @return array
     */
    public function getDeliveryType()
    {
        return [
            'express' => [
                'is_express' => ConfigService::get('delivery_type', 'is_express', 1),
                'express_name' => ConfigService::get('delivery_type', 'express_name', '快递发货'),
            ]
        ];
    }

    /**
     * @notes 删除订单
     * @param $params
     * @return bool
     */
    public function del($params)
    {
        return Order::destroy($params['id']);
    }

    /**
     * @notes 获取不同类型订单的规格单价
     * @param $params
     */
    public static function getSellPrice($params, $goodsInfo)
    {
        switch ($params['order_type']) {
            // 普通订单
            case OrderEnum::NORMAL_ORDER:
                return self::getGoodsSellPrice($goodsInfo);
        }
    }

    /**
     * @notes 获取商品售价
     * @param $params
     * @return mixed
     * @author lgp
     * @date 2022/5/7 18:40
     */
    public static function getGoodsSellPrice($params)
    {
        return $params['sell_price'];
    }

}
