<?php

namespace App\Http\Controllers\V1;

use App\Models\Order;
use App\Models\WarehouseGoods;
use App\Services\Api\OrderService;
use App\Services\Api\GoodsService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class OrderController extends Controller
{
    public function __construct()
    {
        $this->user = auth('api')->user();
        $this->userId = $this->user ? $this->user->id : 0;
    }

    //提交订单
    public function submit(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'remark' => 'min:0|max:100'
        ], [
            'remark.max' => '备注不应超过100个字符',
        ]);
        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }
        if (!$goods = GoodsService::isGoodsCanBuy($request->goods_id)) {
            return $this->error('商品已下架！');
        }
        if (!$res = OrderService::saveOrder($request, $this->userId, $goods)) {
            return $this->error('下单出错！');
        };

        return $this->success();
    }

    //取消订单
    public function delay(Request $request)
    {
        $orderId = $request->order_id;
        $order = Order::find($orderId);
        $order->cancel_status = 1; //1.申请取消 2.已取消
        $order->save();

        return $this->success('', '已申请取消');
    }

    //确认收货
    public function confirm(Request $request)
    {
        $orderId = $request->order_id;
        $order = Order::find($orderId);
        $order->status = 2; //1.进行中 2.已完成
        $order->save();

        return $this->success('', '已确认收货');
    }

    //兑换订单
    public function orderList(Request $request)
    {
        $keyword = $request->input('keyword', null);
        $status = $request->input('status', 0);

        $map[] = ['user_id', '=', $this->userId];
        if($status){
            $map[] = ['status', '=', $status];
        }
        $goodsIds = [];
        if (!empty($keyword)) {
            $goodsIds = GoodsService::getGoodsIds($keyword);
        }

        $list = OrderService::getMyOrderList($map, $request->input('page', 1), $goodsIds);

        return $this->success($list);
    }

    //订单详情
    public function orderDetail(Request $request)
    {
        $orderId = $request->order_id;

        $data = OrderService::getOrderDetail($orderId);

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

    //修改收货地址
    public function changeAddress(Request $request)
    {
        if(!$res = OrderService::changeAddress($request)){
            return $this->error('修改失败!');
        };

        return $this->success('修改成功！');
    }


}
