<?php

namespace App\Http\Controllers\Api;

use App\Command\Log;
use App\Models\Adapay;
use App\Models\UserAddress;
use App\Models\Store;
use App\Models\Good as GoodModel;
use App\Models\User as UserModel;
use App\Models\PaymentRecord;
use App\Models\GoodSku;
use App\Models\OrderGoods;
use App\Models\OrderInfo as OrderInfoModel;
use App\Models\MerchantGoodSku;
use Dcat\Admin\Grid\Displayers\Orderable;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use League\CommonMark\Node\Query\OrExpr;
use App\Handlers\MpAaccessToken;
use DateTime;
use DateTimeZone;
use Exception;

class OrderController extends BaseController
{

    //立即购买-确认订单
    public function CheckoutBuyOrder(Request $request)
    {
        $userObj = $request->user();
        $merchant_id = $userObj->merchant_id ?? 0;
        $goods_id = $request->goods_id;
        $num = $request->num ?? 1;
        $attr_name = $request->attr_name ?? '';
        $goodsObj = GoodModel::find($goods_id);
        if (!$goodsObj) {
            return $this->JsonResponse('', '参数错误', 201);
        }
        $attr_val = '';
        $goods_price = 0;
        if ($attr_name) {
            $attrArr = explode(",", $attr_name);
            utf8_array_asort($attrArr);
            $attrStr = join("、", $attrArr);
            $attr_sn = md5($attrStr);
            $arrObj = GoodSku::where('goods_id', $goods_id)->where('attr_sn', $attr_sn)->first();
            $attr_val = $arrObj ? $arrObj->attr_val : '';
            $attr_id = $arrObj ? $arrObj->id : 0;
            $goods_price = ($arrObj && $goodsObj->goods_type && $merchant_id) ? $arrObj->cg_price : $arrObj->market_price;
        }

        $data = [];
        $data['goods_id'] = $goods_id;
        $data['goods_name'] = $goodsObj->goods_name;
        $data['goods_img'] = $goodsObj->cover_img ? togetherFilePath($goodsObj->cover_img) : '';
        $data['num'] = $num;
        $data['attr_id'] = $attr_id;
        $data['goods_price'] = $goods_price;
        $data['attr_name'] = $attr_val;

        return $this->JsonResponse($data);
    }

    //创建订单--立即购买
    public function CreateBuyOrder(Request $request)
    {
        $orderObj = new OrderInfoModel();
        $userObj = $request->user();
        $user_id = $userObj->id;
        $merchant_id = (int)$userObj->merchant_id; //绑定企业
        $spuid = $userObj->spuid; //直推
        $goods_id = $request->goods_id;
        $num = $request->num ?? 1;
        $attr_id = $request->attr_id ?? 0;
        $delivery_type = $request->delivery_type; // 收货方式 1:代收点 2:送货上门
        $store_id = $request->store_id ?? 0; //代收点 门店ID
        //----收货地址----
        $address = $request->address ?? ''; //详情地址
        $area = $request->area ?? '';
        $phone = $request->phone ? $request->phone : $userObj->phone;
        $consignee = $request->consignee ?? '';
        //$address_id = $request->address_id ?? 0; //地址ID

        $goodsObj = GoodModel::find($goods_id);
        if (!$goodsObj) {
            return $this->JsonResponse('', '参数错误', 201);
        }
        // $userAddress = '';
        // if ($address_id) {
        //     $userAddress = UserAddress::where("id", $address_id)->first();
        // }

        $order_sn = $this->getOrderSn();
        DB::beginTransaction();
        try {
            $total_price = 0;
            $orderGoods = [];
            //商品信息
            $goodObj = GoodModel::find($goods_id);
            $good_price = 0; //商品单价
            //判断是否有规格
            $attr_val = '';
            if ($attr_id) {
                $arrObj = GoodSku::where(['id' => $attr_id, 'goods_id' => $goods_id])->first();
                if (!$arrObj) {
                    return $this->JsonResponse('', '参数错误', 201);
                } else {
                    if ($arrObj->stock < $num) {
                        return $this->JsonResponse('', '该商品库存不足', 500);
                    }
                }
                $attr_val = $arrObj ? $arrObj->attr_val : '';
                $good_price = ($arrObj && $goodsObj->goods_type && $merchant_id) ? $arrObj->cg_price : $arrObj->market_price;
            }
            //商品总价
            $total_price = ($good_price * $num);

            $tmp = [];
            $tmp['goods_id'] = $goods_id;
            $tmp['goods_number'] = $num;
            $tmp['goods_price'] = $good_price;
            $tmp['goods_attr'] = $attr_val;
            $tmp['attr_id'] = $attr_id;
            $tmp['goods_name'] = $goodObj->goods_name;
            $tmp['goods_img'] = $goodObj->cover_img;
            $tmp['merchant_id'] = $merchant_id;
            $tmp['created_at'] = date("Y-m-d H:i:s");
            array_push($orderGoods, $tmp);
            //订单信息
            $orderObj->order_sn = $order_sn;
            $orderObj->user_id = $user_id;
            $orderObj->area = $area;
            $orderObj->address = $address;
            $orderObj->consignee = $consignee;
            $orderObj->mobile = $phone;
            $orderObj->goods_amount = $total_price;
            $orderObj->order_amount = $total_price;
            $orderObj->goods_sn = $goodObj->goods_sn;
            $orderObj->delivery_type = $delivery_type;
            $orderObj->merchant_id = $merchant_id;
            $orderObj->store_id = $store_id;
            $orderObj->is_commission = ($spuid || $merchant_id) ? 1 : 0;
            if ($orderObj->save()) {
                $order_id = $orderObj->id;
                foreach ($orderGoods as $key => $item) {
                    $orderGoods[$key]['order_id'] = $order_id;
                }
                DB::table("li_order_goods")->insert($orderGoods);
            }
            DB::commit();
            //15分钟取消订单
            //$this->dispatch(new CancelOrder($orderObj, 900));
            return $this->JsonResponse(['order_id' => $orderObj->id]);
        } catch (\Exception $exception) {
            Log::add('创建预支付订单失败', $exception->getMessage());
            DB::rollBack();
            return $this->JsonResponse('', '创建预支付订单失败', 201);
        }
    }

    //创建订单
    public function CreateOrder(Request $request)
    {
        $orderObj = new OrderInfoModel();
        $userObj = $request->user();
        $user_id = $userObj->id;
        $merchant_id = $userObj->merchant_id;
        $spuid = $userObj->spuid; //直推
        $catKey = $request->catKey ?? ''; //购物车KeyID拼接 5_1,6_2
        $delivery_type = $request->delivery_type; // 收货方式 1:代收点 2:送货上门
        $store_id = $request->store_id ?? 0; //代收点 门店ID
        //----收货地址----
        $address = $request->address ?? ''; //详情地址
        $area = $request->area ?? '';
        $phone = $request->phone ? $request->phone : $userObj->phone;
        $consignee = $request->consignee ?? '';
        if (!$catKey) {
            return $this->JsonResponse('', '参数错误', 201);
        }

        $shoppingCart = $userObj->shopping_cart ? json_decode($userObj->shopping_cart, true) : [];
        if (empty($shoppingCart)) {
            return $this->JsonResponse('', '购物车无资源', 500);
        }

        $userAddress = '';
        // if ($address_id) {
        //     $userAddress = UserAddress::where(['uid' => $user_id, 'id' => $address_id])->first();
        //     if (!$userAddress) {
        //         return $this->JsonResponse('', '请选择收货地址', 500);
        //     }
        // }
        $order_sn = $this->getOrderSn();
        DB::beginTransaction();
        try {
            $total_price = 0;
            $idsArr = explode(",", $catKey);
            $orderGoods = [];
            $goods_name = '';
            foreach ($idsArr as $key) {
                $cartRow = isset($shoppingCart[$key]) ? $shoppingCart[$key] : [];
                if (!$cartRow) {
                    continue;
                }
                //商品信息
                $goods_id = $cartRow['goods_id'];
                $attr_id = $cartRow['attr_id'];
                $goodsObj = GoodModel::find($goods_id);
                $skuObj = GoodSku::find($attr_id);
                if (!$goodsObj || !$skuObj) {
                    unset($shoppingCart[$key]);
                    continue;
                } else {
                    if ($skuObj->stock < $cartRow['num']) {
                        return $this->JsonResponse('', '该商品库存不足!', 500);
                    }
                }
                $goods_price = ($merchant_id && $goodsObj->goods_type) ? $skuObj->cg_price : $skuObj->market_price;
                $goods_img = isset($goodsObj->cover_img) ? $goodsObj->cover_img  : '';
                $goods_name .= $goodsObj->goods_name . "、";

                $tmp = [];
                $tmp['goods_id'] = $goods_id;
                $tmp['goods_number'] = $cartRow['num'];
                $tmp['goods_price'] = $goods_price;
                $tmp['goods_attr'] = $cartRow['attr_txt'];
                $tmp['attr_id'] =  $attr_id;
                $tmp['goods_name'] = $goodsObj->goods_name;
                $tmp['goods_img'] = $goods_img;
                $tmp['merchant_id'] = $merchant_id;
                $tmp['created_at'] = date("Y-m-d H:i:s");
                array_push($orderGoods, $tmp);
                //总价
                $total_price += ((float)$goods_price * (int)$cartRow['num']);
                //删除购物车商品
                unset($shoppingCart[$key]);
            }
            if ($total_price == 0) {
                return $this->JsonResponse('', '参数错误', 201);
            }
            $orderObj->order_sn = $order_sn;
            $orderObj->user_id = $user_id;
            $orderObj->address = $address;
            $orderObj->area = $area;
            $orderObj->consignee = $consignee;
            $orderObj->mobile = $phone;
            $orderObj->goods_amount = $total_price;
            $orderObj->order_amount = $total_price;
            $orderObj->delivery_type = $delivery_type;
            $orderObj->merchant_id = $merchant_id;
            $orderObj->store_id = $store_id;
            $orderObj->is_commission = ($spuid || $merchant_id) ? 1 : 0;

            if ($orderObj->save()) {
                $order_id = $orderObj->id;
                foreach ($orderGoods as $key => $item) {
                    $orderGoods[$key]['order_id'] = $order_id;
                }
                DB::table("li_order_goods")->insert($orderGoods);
            } else {
                return $this->JsonResponse('', '创建购物车订单失败', 201);
            }
            $userObj->shopping_cart = empty($shoppingCart) ? null : json_encode($shoppingCart, JSON_UNESCAPED_UNICODE);
            $userObj->save();
            DB::commit();

            return $this->JsonResponse(['order_id' => $orderObj->id]);
        } catch (\Exception $exception) {
            Log::add('创建购物车订单失败', $exception->getMessage());
            DB::rollBack();
            return $this->JsonResponse('', '创建购物车订单失败', 201);
        }
    }



    private function getOrderSn()
    {
        $order_sn = '';
        $flag = 0;
        do {
            //'20231229875256'; 
            $order_sn = date('Ymd') . mt_rand(1000, 9999) . substr(implode("", array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
            $rowObj = OrderInfoModel::where('order_sn', $order_sn)->first();
            $flag = $rowObj ? 0 :  1;
        } while ($flag < 1);
        return $order_sn;
    }

    //订单支付
    public function pay(Request $request)
    {

        $order_id = $request->order_id ?? 0;
        $openid = $request->user()->openid;
        DB::beginTransaction();
        try {
            $res = '';
            $order = OrderInfoModel::find($order_id);
            if ($order->pay_cs > 0 && $order->pay_cs < 20) {
                $order_record = $order->order_record ?? $order->order_sn;
                $order->order_sn = $this->getOrderSn();
                $order->order_record = $order_record . "|" . $order->order_sn;
                $order->save();
            }
            $orderGoodsObj = OrderGoods::where("order_id", $order_id)->first();
            $order_title = $orderGoodsObj ? $orderGoodsObj->goods_name : '';
            Log::add('--支付订单号ID--', ['order_id' => $order_id, 'order_sn' => $order->order_sn]);
            $res = (new Adapay())->pay($order_title, $order->order_sn, $order->order_amount, $openid);
            $order->pay_cs += 1;
            $order->save();

            DB::commit();
            return $this->JsonResponse($res);
        } catch (\Exception $exception) {
            Log::add('拉起微信支付失败', $exception->getMessage());
            return $this->JsonResponse('', $exception->getMessage(), 500);
        }
    }

    //付款回调
    public function payNotify(Request $request)
    {
        Log::add('--支付回调结果--', $_POST);
        $fields = $_POST ?? [];
        //$result = file_get_contents('php://input');
        return $this->JsonResponse((new Adapay())->payNotify($fields));
    }


    // 已完成:用户点击确认收货或发货后3天,自动变更为已完成状态
    // 售后:已完成状态下48小时内展示申请售后按钮,可申请售后,如超过48小时,则不展示申请售后按钮
    public function orderList(Request $request)
    {
        $status = $request->order_status ?? -1;
        $page = $request->page ?? 1;
        $limit = $request->limit ?? 10;

        $sql = OrderInfoModel::where(['user_id' => $request->user()->id, 'deleted_at' => null]);

        if ($status >= 0) {
            $sql = $sql->where(['order_status' => $status]);
        }
        $total = $sql->count();
        $data = [
            'total' => $total,
            'total_page' => ceil($total / $limit),
            'list' => []
        ];
        $listData = $sql->offset(($page - 1) * $limit)->limit($limit)->orderBy('created_at', 'DESC')->get();
        if ($listData->toArray()) {
            foreach ($listData as $item) {
                //订单商品
                $order_goods = [];
                $ogoods = OrderGoods::where(["order_id" => $item->id])->limit(1)->get();
                foreach ($ogoods as $key => $valObj) {
                    $tmp = [];
                    $tmp['og_id'] = $valObj->id;
                    $tmp['goods_id'] = $valObj->goods_id;
                    $tmp['goods_name'] = $valObj->goods_name;
                    $tmp['goods_number'] = $valObj->goods_number;
                    $tmp['goods_attr'] = $valObj->goods_attr;
                    $tmp['goods_price'] = $valObj->goods_price;
                    $tmp['goods_img'] = $valObj->goods_img ? togetherFilePath($valObj->goods_img) : '';
                    $tmp['is_comment'] = $valObj->is_comment;
                    array_push($order_goods, $tmp);
                }
                $data['list'][] = [
                    'order_id' => $item->id,
                    'order_sn' => $item->order_sn,
                    'order_status' => $item->order_status,
                    'status_txt' => OrderInfoModel::STATUS_OPTIONS[$item->order_status],
                    //'is_apply' => $is_apply,
                    //'service_status' => $item->service_status,
                    'order_amount' => $item->order_amount,
                    'verification_code' => $item->verification_code ?? '',
                    'created_at' => date("Y-m-d H:i", strtotime($item->created_at)),
                    'order_goods' => $order_goods
                ];
            }
        }
        return $this->JsonResponse($data);
    }

    public function canceOrder(Request $request)
    {
        $order_id = $request->order_id ?? null;
        $model = OrderInfoModel::find($order_id);
        if (!$model) {
            return $this->JsonResponse('', '参数错误', 201);
        }
        if ($model->user_id != $request->user()->id) {
            return $this->JsonResponse('', '非本人订单', 201);
        }
        if (!in_array($model->order_status, [0, 1])) {
            return $this->JsonResponse('', '不满足取消条件' . $model->order_status, 500);
        }
        DB::beginTransaction();
        try {
            //代到货订单--退库存
            if ($model->order_status == 1) {
                //更新商品库存
                $goodsList = OrderGoods::where("order_id", $order_id)->get();
                foreach ($goodsList as $item) {
                    $gid = $item->goods_id;
                    $attr_id = $item->attr_id;
                    $mer_id = $item->merchant_id;
                    $goods_number = $item->goods_number;

                    $goodsObj = GoodModel::find($gid);
                    //更新商品规格库存
                    $attrObj = GoodSku::find($attr_id);
                    $attr_stock = $attrObj->stock + $goods_number;
                    $attrObj->stock = $attr_stock;
                    $attrObj->save();
                    //更新商品sku
                    $skuArr = json_decode($goodsObj->sku, true);
                    if ($skuArr['sku']) {
                        foreach ($skuArr['sku'] as $kk => $vv) {
                            if (isset($vv['attr_sn']) && $vv['attr_sn'] == $attrObj->attr_sn) {
                                $skuArr['sku'][$kk]['stock'] = $attr_stock;
                            }
                        }
                        $goodsObj->sku = json_encode($skuArr, JSON_UNESCAPED_UNICODE);
                        $goodsObj->save();
                    }
                    //商户规格库存
                    $mgsObj = MerchantGoodSku::where(['goods_id' => $gid, 'attr_id' => $attr_id, 'merchant_id' => $mer_id])->first();
                    if ($mer_id && $mgsObj) {
                        $changeStock = $mgsObj->stock + $goods_number;
                        $mgsObj->stock = $changeStock;
                        $mgsObj->save();
                    }
                }
            }
            //待发货订单--退款
            if ($model->order_status == 1 && $model->order_amount > 0) {
                $order_sn = $model->order_sn;
                $refund_no = "R" . date("YmdHis") . rand(100000, 999999); //退单号
                $result = (new Adapay())->refund($order_sn, $refund_no);
            }
            $model->order_status = 7;
            $model->save();

            DB::commit();
        } catch (\Exception $exception) {
            DB::rollBack();
            Log::add('取消订单失败', $exception->getMessage());
            return $this->JsonResponse('', '取消订单失败', 201);
        }
        return  $this->JsonResponse('');
    }

    public function delOrder(Request $request)
    {
        $order_id = $request->order_id ?? null;
        $model = OrderInfoModel::find($order_id);
        if (!$model) {
            return $this->JsonResponse('', '参数错误', 201);
        }
        if ($model->user_id != $request->user()->id) {
            return $this->JsonResponse('', '非本人订单', 201);
        }
        $model->delete();

        return  $this->JsonResponse('');
    }

    //确认收货(订单完成)
    // public function completeOrder(Request $request)
    // {
    //     $order_id = $request->order_id ?? null;
    //     if (!$order_id) {
    //         return $this->JsonResponse('', '参数错误', 201);
    //     }

    //     $model =  OrderInfoModel::find($order_id);
    //     if ($model->user_id != $request->user()->id) {
    //         return $this->JsonResponse('', '非本人订单', 201);
    //     }
    //     $model->shipping_status = 2;
    //     $model->order_status = 2;
    //     $model->received_at = date("Y-m-d H:i:s");
    //     $model->save();
    //     return  $this->JsonResponse('');
    // }

    //扫码核销
    public function scanCodeVerifi(Request $request)
    {
        $mpTokenObj = new MpAaccessToken();
        $dateTime = new DateTime();
        $dateTime->setTimezone(new DateTimeZone('Asia/Shanghai'));
        $upload_time = $dateTime->format('Y-m-d\TH:i:s.vP');

        $verObj = $request->user();
        $code = $request->code ?? '';
        $orderObj = OrderInfoModel::where('verification_code', $code)->first();
        if (!$orderObj) {
            return $this->JsonResponse('', '参数错误', 201);
        }
        //核销员所属门店
        $hx_store = $useObj->store_id ?? 0;
        if ($verObj->role_id != 2 || $orderObj->store_id != $hx_store) {
            //return $this->JsonResponse('', '核销码不匹配门店', 500);
        }

        Log::add('核销操作', [$orderObj->verification_at]);
        if (!$orderObj->verification_at) {
            $orderObj->order_status = 3;
            $orderObj->verifier_id = $verObj->id;
            $orderObj->verifier = $verObj->name;
            $orderObj->verification_at = date("Y-m-d H:i:s");
            //$orderObj->save();
            try {
                //接入微信小程序发货管理
                Log::add('是否核销126', []);
                //付款记录
                $recordObj = PaymentRecord::where('order_sn', $orderObj->order_sn)->first();
                if (!$recordObj) {
                    throw new Exception('该订单尚未支付');
                }
                $transaction_id = $recordObj->other_order;
                $payerOpenid = UserModel::where('id', $recordObj->uid)->value('openid');
                //商品信息
                $ogItem = DB::table('li_order_goods')
                    ->select(DB::raw('GROUP_CONCAT(goods_name) as shipping_goods'))
                    ->where('order_id', $orderObj->id)
                    ->first();

                $access_token = $mpTokenObj->getAccessToken();
                $url = "https://api.weixin.qq.com/wxa/sec/order/upload_shipping_info?access_token=" . $access_token;
                $data = [
                    "order_key" => [
                        "order_number_type" => 2,
                        "transaction_id" => $transaction_id,
                    ],
                    "logistics_type" => 4, //4、用户自提
                    "delivery_mode" => 1, //1、(统一发货)
                    "shipping_list" => [
                        ["item_desc" => $ogItem->shipping_goods]
                    ],
                    "upload_time" => $upload_time,
                    "payer" => [
                        "openid" => $payerOpenid,
                    ]
                ];

                $result = curl_post_request($url, $data);
                Log::add('发货录入', $result);
                if ($result['errcode'] != 0) {
                    throw new Exception($result['errmsg']);
                } else {
                    $orderObj->shipping_type = 4;
                    $orderObj->shipping_goods = $ogItem->shipping_goods;
                    $orderObj->shipping_at = date("Y-m-d H:i:s");
                    $orderObj->save();
                }

                DB::commit();
            } catch (Exception $e) {
                DB::rollBack();
                return  $this->JsonResponse('', $e->getMessage(), 500);
            }
        } else {
            return  $this->JsonResponse('', '该码已核销,无需多次重复扫码', 500);
        }
        Log::add('核销操作', $orderObj->toArray());
        return  $this->JsonResponse('');
    }

    //扫码核销展示详情
    public function scanCodeDetail(Request $request)
    {
        $useObj = $request->user();
        $code = $request->code ?? '';
        $orderObj = OrderInfoModel::where('verification_code', $code)->first();
        if (!$orderObj) {
            Log::add('核销码', $code);
            return $this->JsonResponse('', '参数错误', 201);
        }
        //核销员所属门店
        $hx_store = $useObj->store_id ?? 0;
        if ($useObj->role_id != 2 || $orderObj->store_id != $hx_store) {
            //return $this->JsonResponse('', '核销码不匹配门店', 500);
        }
        $order_id = $orderObj->id;
        //商品信息
        $order_goods = $this->getOrderGoods($order_id);
        //快递待收点、收货地址
        $delivery = [];
        if ($orderObj->address) {
            $delivery['contacts'] = $orderObj->consignee;
            $delivery['phone'] = $orderObj->mobile;
            $delivery['area'] = $orderObj->area . "(" . $orderObj->address . ")";
            $delivery['lat'] = '';
            $delivery['lng'] = '';
        }
        if ($orderObj->store_id) {
            $sObj = Store::find($orderObj->store_id);
            $lat_lng = $sObj->lat_lng; //121.47,31.23
            $latlngArr = $lat_lng ? explode(",", $lat_lng) : [];
            $delivery['contacts'] = $sObj->contacts;
            $delivery['phone'] = $sObj->phone;
            $delivery['address'] = $sObj->address;
            $delivery['lat'] = isset($latlngArr[0]) ? $latlngArr[0] : '';
            $delivery['lng'] = isset($latlngArr[1]) ? $latlngArr[1] : '';
        }

        $data = [
            'id' => $order_id,
            'order_sn' => $orderObj->order_sn,
            'user_id' => $orderObj->user_id,
            'order_amount' => $orderObj->order_amount,
            //'mobile' => $orderObj->mobile,
            'delivery' => $delivery,
            'delivery_type' => $orderObj->delivery_type,
            'delivery_typename' => ($orderObj->delivery_type == 1) ? '快递代收点' : '送货上门',
            'created_at' => date("Y-m-d H:i:s", strtotime($orderObj->created_at)),
            'order_goods' => $order_goods
        ];
        return $this->JsonResponse($data);
    }

    //订单详情
    public function OrderInfo(Request $request)
    {
        $order_id = $request->order_id ?? 0;
        $orderObj = OrderInfoModel::find($order_id);
        if (!$orderObj) {
            return $this->JsonResponse('', '参数错误', 201);
        }
        $user_id = $request->user()->id;
        if ($orderObj->user_id != $user_id) {
            return $this->JsonResponse('', '非本人订单', 201);
        }

        //商品信息
        $order_goods = $this->getOrderGoods($order_id);
        //快递待收点、收货地址
        $delivery = [];
        if ($orderObj->consignee) {
            //$addressObj = UserAddress::find($orderObj->address_id);
            $delivery['contacts'] = $orderObj->consignee;
            $delivery['phone'] = $orderObj->mobile;
            $delivery['address'] = $orderObj->address;
            $delivery['area'] = $orderObj->area;
            // $delivery['lat'] = $addressObj->lat;
            // $delivery['lng'] = $addressObj->lng;
        }
        if ($orderObj->store_id) {
            $sObj = Store::find($orderObj->store_id);
            $lat_lng = $sObj->lat_lng; //121.47,31.23
            $latlngArr = $lat_lng ? explode(",", $lat_lng) : [];
            $delivery['contacts'] = $sObj->contacts;
            $delivery['phone'] = $sObj->phone;
            $delivery['address'] = $sObj->address;
            $delivery['lat'] = isset($latlngArr[0]) ? $latlngArr[0] : '';
            $delivery['lng'] = isset($latlngArr[1]) ? $latlngArr[1] : '';
        }
        //订单状态
        $order_status = $orderObj->order_status;
        $status_txt = OrderInfoModel::STATUS_OPTIONS[$order_status];

        $data = [
            'id' => $orderObj->id,
            'order_sn' => $orderObj->order_sn,
            'user_id' => $orderObj->user_id,
            'order_amount' => $orderObj->order_amount,
            'mobile' => $orderObj->mobile,
            'order_status' => $order_status,
            'status_txt' => $status_txt,
            'verification_code' => $orderObj->verification_code ?? '',
            'delivery' => $delivery,
            'delivery_type' => $orderObj->delivery_type,
            'delivery_typename' => ($orderObj->delivery_type == 1) ? '快递代收点' : '送货上门',
            'created_at' => date("Y-m-d H:i:s", strtotime($orderObj->created_at)),
            'order_goods' => $order_goods
        ];
        return $this->JsonResponse($data);
    }

    //订单商品信息
    private function getOrderGoods($oid)
    {
        $order_goods = [];
        $ogoods = OrderGoods::where(["order_id" => $oid])->get();
        foreach ($ogoods as $key => $valObj) {
            $tmp = [];
            $tmp['og_id'] = $valObj->id;
            $tmp['goods_id'] = $valObj->goods_id;
            $tmp['goods_name'] = $valObj->goods_name;
            $tmp['goods_number'] = $valObj->goods_number;
            $tmp['goods_attr'] = $valObj->goods_attr;
            $tmp['goods_price'] = $valObj->goods_price;
            $tmp['is_comment'] = $valObj->is_comment;
            $tmp['goods_img'] = $valObj->goods_img ? togetherFilePath($valObj->goods_img) : '';
            array_push($order_goods, $tmp);
        }
        return $order_goods;
    }

    //购物车确认订单
    public function CheckoutCartOrder(Request $request)
    {
        $cartKey = $request->cartKey ?? ''; //商品ID拼接 5_1,6_1
        if (!$cartKey) {
            return $this->JsonResponse('', '请选择购物车商品', 500);
        }
        $gidArr = explode(",", $cartKey);
        $user = $request->user();
        $shoppingCart = $user->shopping_cart ? json_decode($user->shopping_cart, true) : [];
        $data = [];
        foreach ($shoppingCart as $kk => $item) {
            $tmp = [];
            if (!in_array($kk, $gidArr)) {
                continue;
            }
            $goodsObj = GoodModel::find($item['goods_id']);
            $tmp['catKey'] = $kk;
            $tmp['goods_id'] = $item['goods_id'];
            $tmp['goods_name'] = $goodsObj->goods_name;
            $tmp['num'] = $item['num'];
            $tmp['goods_price'] = sprintf('%.2f', $item['goods_price']);
            $tmp['attr_name'] = $item['attr_txt'];
            $tmp['goods_img'] = $goodsObj->cover_img ? togetherFilePath($goodsObj->cover_img) : '';
            $tmp['attr_id'] = $item['attr_id'];

            array_push($data, $tmp);
        }
        return $this->JsonResponse($data);
    }

    //商户端首页统计
    public function orderCollect(Request $request)
    {
        $muser = $request->user();
        $merchant_id = $muser->merchant_id;
        //订单状态 0:待付款 1:待到货 2:待领取 3: 待评价 4:已完成  7:已取消 8:已退款
        $where = ['merchant_id' => $merchant_id];
        $firstDayOfMonth = date('Y-m-01 00:00:00'); // 00:00:00
        $lastDayOfMonth = date("Y-m-t 23:59:59", time());
        //本月数据统计
        $currentMonth = [];
        $currentMonth['buyCount'] = OrderInfoModel::where($where)->where('pay_status', 1)->whereBetween('created_at', [$firstDayOfMonth, $lastDayOfMonth])->count();
        $currentMonth['pickedCount'] = OrderInfoModel::where($where)->where('pay_status', 1)->whereIn('order_status', [3, 4])->whereBetween('created_at', [$firstDayOfMonth, $lastDayOfMonth])->count();
        $currentMonth['waitCount'] = OrderInfoModel::where($where)->where('pay_status', 1)->where("order_status", 2)->whereBetween('created_at', [$firstDayOfMonth, $lastDayOfMonth])->count();
        $currentStock = MerchantGoodSku::where($where)->sum('stock');
        $currentMonth['stockCount'] = $currentStock;

        //上月数据统计
        $lastMonth = [];
        if (date('d') < 10) {
        }
        $firstDayOfLastMonth = date('Y-m-01 00:00:00', strtotime('-1 month', time()));
        $ninthDayOfLastMonth = date('Y-m-t 23:59:59', strtotime('-1 month', time()));
        $lastMonth['buyCount'] = OrderInfoModel::where($where)->where('pay_status', 1)->whereBetween('created_at', [$firstDayOfLastMonth, $ninthDayOfLastMonth])->count();
        $lastMonth['pickedCount'] = OrderInfoModel::where($where)->where('pay_status', 1)->whereIn('order_status', [3, 4])->whereBetween('created_at', [$firstDayOfLastMonth, $ninthDayOfLastMonth])->count();
        $lastMonth['waitCount'] = OrderInfoModel::where($where)->where('pay_status', 1)->where("order_status", 2)->whereBetween('created_at', [$firstDayOfLastMonth, $ninthDayOfLastMonth])->count();
        //本月订单商品销量
        $goods_number = OrderGoods::where(['merchant_id' => $merchant_id, 'is_pay' => 1])
            ->whereBetween('created_at', [$firstDayOfMonth, $lastDayOfMonth])->sum('goods_number');
        $lastMonth['stockCount'] = $goods_number + $currentStock;

        return $this->JsonResponse(['current' => $currentMonth ? $currentMonth : new \stdClass(), 'last' => $lastMonth ? $lastMonth : new \stdClass()]);
    }
}