<?php

namespace Modules\Mall\Http\Controllers\Admin\Action\Order;

use Encore\Admin\Actions\Response;
use Encore\Admin\Actions\RowAction;
use Illuminate\Http\Request;
use Modules\Mall\Models\Express;
use Modules\Mall\Models\Order;
use Modules\Mall\Models\OrderExpress;

class Delivered extends RowAction
{

    public $name = '商品发货';

    public function handle(Order $order, Request $request): Response
    {
        if ($request->type == OrderExpress::TYPE_EXPRESS && (empty($request->express_id) || empty($request->express_no))) {
            return $this->response()->error('缺少快递公司或快递单号');
        }

        $result = $order->deliver($request->express_id, $request->express_no, $request->type, $request->person);
        if ($result === true) {
            return $this->response()->success('发货成功')->refresh();
        } else {
            return $this->response()->error('失败');
        }
    }

    public function form()
    {
        $order     = Order::find($this->getKey());
        $expresses = $order->shop->expresses()->pluck('name', 'id');

        $this->select('type', '方式')
            ->options(OrderExpress::TYPE_MAP)
            ->required();

        $this->select('express_id', '物流')
            ->options($expresses);
        $this->text('express_no', '物流单号');
        $this->text('person', '经办人');
    }

}
