<?php

namespace App\Admin\Extensions\ToolBar\Forms\Shop;

use App\Models\Shop\ShopOrderRefund;
use App\Models\Shop\ShopSubOrder;
use App\Service\Shop\ShopService;
use Dcat\Admin\Admin;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;

class OrderRefundApplyForm extends Form implements LazyRenderable
{
    use LazyWidget;

    public function form()
    {
        $this->textarea('orderId', __('订单号'))->placeholder('请添加订单号，多个单号请换行，一行一个')->rows(8)->required();
        // $this->text('subOrderId', __('子订单号'))->width('200px')->required();
        $this->radio('reasonId', __('退款原因ID'))->options(ShopOrderRefund::REFUND_REASON_ID_MAP)->required();
        $this->text('detail', __('退款说明'))->default('');
    }

    public function handle(array $input)
    {
        if (! Admin::user()->inRoles(['administrator', 'adminNormal', 'operatorAdmin'])) {
            return $this->response()->error('抱歉，您没有权限操作~');
        }
        $orderId = $input['orderId'];
        // $subOid     = $input['subOrderId'];
        $reasonId = $input['reasonId'];
        $detail = $input['detail'];

        if (! $orderId) {
            return $this->response()->error('订单号不能为空');
        }
        $orderIds = clean_ids($orderId, true);
        if (count($orderIds) <= 0) {
            return $this->response()->error('订单号不能为空')->refresh();
        }
        if ($reasonId < 100) {
            return $this->response()->error('退款原因ID不正确');
        }
        if (! $detail) {
            return $this->response()->error('退款说明不能为空');
        }
        $orderList = (new ShopSubOrder())->getListByOrdIds($orderIds, ['id', 'order_id']);

        // 批量申请退款
        foreach ($orderList as $v) {
            $flag = ShopOrderRefund::where('order_id', $v['order_id'])->exists();
            if ($flag) {
                continue;
            }
            try {
                ShopService::applyRefund($v['id'], $reasonId, $detail);
            } catch (\Exception $e) {
                return $this->response()->error("申请错误。订单号[{$v['order_id']}]：".($e->getMessage()));
            }
        }

        return $this->response()->success('退款申请已提交')->refresh();

    }
}
