<?php

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

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

class ManualAddProductForm extends Form implements LazyRenderable
{
    use LazyWidget;

    public function form()
    {
        $this->textarea('sku_ids', 'SKU ID (多个ID使用 逗号或空格或tab 连接')->placeholder('如：56123,56125')->attribute('id', 'batch-ids')->required(); //批量选择的行的id通过隐藏元素 提交时一并传递过去
        $this->text('remark', __('批量备注'))->width('400px')->default('');
        $this->text('rank', __('排序权重'))->width('200px')->default(10);
    }

    public function handle(array $input)
    {
        $skuIds = $input['sku_ids'];
        $rank = $input['rank'];
        $remark = trim($input['remark']);
        if ($rank < 1) {
            $rank = 10;
        }

        $skuIds = clean_ids($skuIds, true);

        $errMsg = [];
        foreach ($skuIds as $k => $skuId) {
            if ($skuId < 10000) {
                $errMsg[] = "skuID错误($skuId)";
                unset($skuIds[$k]);
            }
        }

        if (! $skuIds) {
            return $this->response()->error('skuID不能为空')->refresh();
        }
        $newProductIds = [];
        foreach ($skuIds as $skuId) {
            $newProductIds[] = ShopService::fetchAndSaveProductInfo($skuId, $rank, $remark);
        }
        $newProductIdsString = implode(',', $newProductIds);

        return $this->response()->alert(true)->success('添加商品成功。新ID：')->detail($newProductIdsString)->refresh();

    }
}
