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

namespace app\api\logic\twoshop;

use app\common\logic\BaseLogic;
use app\common\model\User;
use app\common\model\UserAddress;
use app\common\enum\DeliveryEnum;
use app\common\model\TwoGoods;
use app\common\model\TwoGoodsItem;
use app\common\model\TwoOrderGoods;
use app\common\model\TwoOrder;
use app\common\model\TwoOrderLog;

use app\common\enum\AfterSaleEnum;
use app\common\enum\AfterSaleLogEnum;
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\OrderLog;
use app\common\model\Region;
use app\common\service\after_sale\AfterSaleService;
use app\common\service\ConfigService;
use app\common\service\FileService;
use expressage\Kd100;
use expressage\Kdniao;
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);
            $goods = self::getOrderGoodsData($params);
            // dd($goods);
            //判断是否需要地址
            $is_address = 1;
           
            //计算运费
            self::$orderPrice['express_price'] = FreightLogic::calculateFreight($goods, $userAddress);
            
            
            self::$orderPrice['total_amount'] = $goods['sell_price'] * $params['goods']['goods_num'];
            self::$orderPrice['order_amount'] = $goods['sell_price'] * $params['goods']['goods_num'];

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

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

            
            $result = [
                'sell_user_id'          => $goods['user_id'],
                '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'                 => $goods,
                '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('请选择收货地址');
        }

        if ($params['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 = TwoGoods::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']);
            // echo 3;die;
            

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

            //订单日志
            (new TwoOrderLog())->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($goods)
    {

        $goodsItem = TwoGoodsItem::where(['id' => $goods['item_id']])->findOrEmpty()->toArray();
        if ($goodsItem['stock'] < $goods['goods_num']) {
            throw new \Exception('商品库存不足');
        }
        //更新商品总库存
        TwoGoods::where('id', $goods['goods_id'])->dec('total_stock', $goods['goods_num'])->save();
        //更新规格库存
        TwoGoodsItem::where('id', $goods['item_id'])->dec('stock', $goods['goods_num'])->save();
    }

    /**
     * @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)
    {
        $params['address'] = $params['address']->toArray();
        $order_data = [
            'sell_user_id'      => $params['sell_user_id'],
            'sn'                => generate_sn((new TwoOrder()), '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']
        ];
        // dd($order_data);
        $order = TwoOrder::create($order_data);


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

        // dd($goods);

        $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'       => $params['order_amount'],
            'total_pay_price'   => $params['order_amount'],//实际支付商品金额(扣除优惠金额)
            '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,
            'sell_user_id'        => $goods['user_id'],
        ];
        
        // dd($goodsData);
        TwoOrderGoods::create($goodsData);
        
        // dd(22);
        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.is_address','user_id',
        ];

        $goodsData = (new TwoGoods())->alias('g')
            ->join('two_goods_item gi', 'gi.goods_id = g.id')
            ->where('gi.id', $params['goods']['item_id'])
            ->field($field)
            ->find()->toArray();
            // ->column($field, 'gi.id');

        $goodsData['goods_num'] = $params['goods']['goods_num'];

        return $goodsData;

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

        // dd($goodsData);

        
        // $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 TwoOrder())->with(['order_goods' => function ($query) {
            $query->append(['goods_image', 'spec_value_str','original_price'])->hidden(['goods_snap']);
        }])
        ->where(['id' => $params['id']])
        ->whereOr([['user_id','=',$params['user_id']], ['sell_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();

        $oresult = $result;
        $result = $result->toArray();

        $result['sell_user'] = [];
        $result['sell_user']['id'] = $oresult->orderGoods->sellUser['id'];
        $result['sell_user']['nickname'] = $oresult->orderGoods->sellUser['nickname'];
        $result['sell_user']['avatar'] = $oresult->orderGoods->sellUser['avatar'];
        $result['sell_user']['login_time'] = $oresult->orderGoods->sellUser['login_time'];
        $result['sell_user']['last_online_time'] = $oresult->orderGoods->sellUser['last_online_time'];
        $result['sell_user']['user_level'] = $oresult->orderGoods->sellUser['user_level'];

        //订单类型
        $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;

        $goods = $result['order_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;

        // dd($result);

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


    /**
     * @notes 取消订单
     * @param $params
     * @return bool
     */
    public static function cancelOrder($params)
    {
        Db::startTrans();
        try {
            $order = (new TwoOrder())->getUserOrderById($params['id'], $params['user_id']);
            // dd( $order->toArray());
            //处于已支付状态的发起整单售后
            // if ($order['pay_status'] == PayEnum::ISPAID) {
            //     AfterSaleService::orderRefund([
            //         'order_id' => $params['id'],
            //         'scene' => AfterSaleLogEnum::BUYER_CANCEL_ORDER
            //     ]);
            // }

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

            // 退还库存
            $orderGoods = TwoOrderGoods::where(['order_id' =>$order['id']])->select()->toArray();
            foreach($orderGoods as $item) {
                $goods = TwoGoods::findOrEmpty($item['goods_id']);
                if($goods->isEmpty()){
                    continue;
                }
                $goodsItem = TwoGoodsItem::findOrEmpty($item['item_id']);
                $goodsItem->stock = $goodsItem->stock + $item['goods_num'];
                $goodsItem->save();
                $goods->total_stock = $goods->total_stock + $item['goods_num'];
                $goods->save();
            }
            //订单日志
            (new TwoOrderLog())->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)
    {
        //更新订单状态
        TwoOrder::update([
            'order_status' => OrderEnum::STATUS_FINISH,
            'confirm_take_time' => time(),
            'after_sale_deadline' => self::getAfterSaleDeadline(), //售后截止时间
        ], ['id' => $params['id'], 'user_id' => $params['user_id']]);

        //订单日志
        (new TwoOrderLog())->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 = TwoOrder::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')
        //     // ->field('g.image,o.order_status,o.total_num,o.address,o.confirm_take_time,o.express_time,o.pay_time,o.create_time')
        //     ->append(['delivery_address'])
        //     ->where(['o.id' => $params['id'], 'o.user_id' => $params['user_id']])
        //     ->find();

        $order = TwoOrder::with(['orderGoods','express'])
        ->where('id',$params['id'])
        ->where('user_id',$params['user_id'])
        ->find();
        if(!$order){
            $order = TwoOrder::with('orderGoods')
            ->where('id',$params['id'])
            ->where('sell_user_id',$params['user_id'])
            ->find();
        }
        $oorder = $order;
        $order = $order->toArray();

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

            $shipment = [
                'title' => '已发货',
                'tips' => '商品已出库',
                'time' => !is_int($order['express_time'])?$order['express_time']:date('Y-m-d H:i:s',$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));
                }
                // dd($traces);
                // $traces = $expressage->logisticsFormat();
                if ($traces != false) {
                    foreach ($traces as &$item) {
                        $item = array_values(array_unique($item));
                    }
                }
            }
        // }

        // 组装数据返回
        return [
            'order' => [
                'goods_image' => $oorder->orderGoods->goods_snap['image'],
                'goods_count' => $order['total_num'],
                'express_name' => $order['express_name'] ?? \app\common\model\Express::where('id', $order['express_id'])->value('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) ? !is_int($order['confirm_take_time'])?$order['confirm_take_time']:date('Y-m-d H:i:s',$order['confirm_take_time']) : '',
            ],
            'delivery' => [
                'title' => '运输中',
                'traces' => $traces
            ],
            'shipment' => $shipment,
            'pay' => [
                'title' => '已支付',
                'tips' => '订单支付成功，等待商家发货',
                'time' => !is_int($order['pay_time'])?$order['pay_time']:date('Y-m-d H:i:s',$order['pay_time'])
            ],
            'buy' => [
                'title' => '已下单',
                'tips' => '订单提交成功',
                'time' => !is_int($order['create_time'])?$order['create_time']:date('Y-m-d H:i:s',$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 TwoOrder::destroy($params['id']);
    }

    /**
     * @notes 获取不同类型订单的规格单价
     * @param $params
     */
    public static function getSellPrice($params, $goodsInfo)
    {
        switch ($params['order_type']) {
            // 普通订单
            case OrderEnum::NORMAL_ORDER:
                // echo '普通订单';die;
                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'];
    }

}
