<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 22/05/10
 * Time: 14:23
 */

namespace App\Services\Api;

use App\Models\Goods;
use App\Models\GoodsAttr;
use App\Models\Order;
use App\Models\UserAddress;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\DB;
use PHPUnit\Util\Exception;

class OrderService
{
    //订单提交
    public static function saveOrder($request, $userId, $goods)
    {
        $userAddress = UserAddress::find($request->address_id);

        $order = App::make('getOrderInstance');
        $order->user_id = $userId;
        $order->goods_id = $request->goods_id;
        $order->goods_attr_id = $request->goods_attr_id;
        $order->num = $request->num;
        $order->total_integral = $request->integral * $request->num;
        $order->reamrk = $request->input('remark', '');
        $order->receiver = $userAddress->name;
        $order->receiver_address = $userAddress->address;
        $order->receiver_mobile = $userAddress->mobile;
        $order->order_no = self::createOrderSn();
        $order->created_at = date('Y-m-d H:i:s');

        if (!$order->save()) {
            return false;
        }
        return true;
    }

    //生成单号：年月日时分秒毫秒 + 4位随机数 如 202205101604398525623
    public static function createOrderSn($prefix = '')
    {
        $utimestamp = microtime(true);
        $timestamp = floor($utimestamp);
        $milliseconds = round(($utimestamp - $timestamp) * 1000);

        return $prefix . date(preg_replace('`(?<!\\\\)u`', $milliseconds, 'YmdHisu'), $timestamp) . rand(1000, 9999);
    }

    //获取订单列表
    public static function getMyOrderList($map = [], $page = 1, $goodsIds = [])
    {
        $limit = 20;
        $offset = ($page - 1) * $limit;

        $query = Order::query()->with('goods:id,name,img,integral');

        if (!empty($goodsIds)) {
            $query->whereIn('goods_id', $goodsIds);
        }
        $list = $query->when($map, function ($query, $map) {
                $query->where($map);
            })
            ->select('id', 'user_id', 'goods_id', 'goods_attr_id', 'order_no', 'num', 'integral', 'created_at')
            ->offset($offset)
            ->limit($limit)
            ->get();

        return $list;
    }

    //订单信息
    public static function getOrderDetail($orderId)
    {
        $order = Order::query()
            ->with('goods:id,name,img,integral')
            ->where('id', $orderId)
            ->first();

        $order = $order->makeHidden('updated_at', 'deleted_at');

        return $order;
    }

    //修改收货地址
    public static function changeAddress($request)
    {
        $order = Order::find($request->order_id);
        $order->name = $request->name;
        $order->mobile = $request->mobile;
        $order->address = $request->address;

        // 要考虑跨区收费....

        if (!$order->save()) {
            return false;
        }

        return true;
    }

}