<?php

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

use App\Models\Shop\ShopAlipayProduct;
use App\Service\Shop\AlipayProductService;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;

class AlipayProductSyncBatchForm extends Form implements LazyRenderable
{
    use LazyWidget;

    public function form()
    {
        $this->textarea('product_ids', '商品ID (多个ID使用 逗号或空格或tab 连接')->placeholder('如：308043,308042的6位数编码')->attribute('id', 'batch-ids')->required(); //批量选择的行的id通过隐藏元素 提交时一并传递过去
        $this->radio('push_type', '推送数据类型')->options(AlipayProductService::OPT_TYPE_MAP)->required();
        $this->radio('page_model', '详情模式')->options(ShopAlipayProduct::PAGE_MODEL_MAP)->required()->help('官方[官方插件版详情页]，自有[自定义详情页版]');
    }

    public function handle(array $input)
    {
        $productIds = $input['product_ids'];
        $productIdsArray = clean_ids($productIds, true);
        if (! $productIdsArray) {
            return $this->response()->error('请选择至少一个商品')->refresh();
        }
        $pushType = $input['push_type'];
        $pageModel = $input['page_model'];
        $isAsync = true; // 是否异步推送

        if (! in_array($pushType, AlipayProductService::OPT_TYPE_LIST)) {
            return $this->response()->error('推送数据类型不正确');
        }
        $tip = AlipayProductService::OPT_TYPE_MAP[$pushType];
        try {
            foreach ($productIdsArray as $productId) {
                AlipayProductService::pushProductToAlipay($productId, $pushType, $pageModel, $isAsync);
            }
        } catch (\Exception $e) {
            return $this->response()->error("推送[{$tip}]到支付宝商品库失败：".$e->getMessage());
        }

        return $this->response()->alert(true)->success("推送[{$tip}]到支付宝商品库完成，请稍后查看推送情况")->refresh();

    }
}
