<?php

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

use App\Models\Common\SysConfig;
use App\Models\Shop\ShopProduct;
use App\Service\System\SystemConfigService;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Alert;
use Dcat\Admin\Widgets\Form;

class AddSpecProductForm extends Form implements LazyRenderable
{
    use LazyWidget;

    public function form()
    {
        $info = '1、只能选择同一个小程序的商品<br />2、添加完成后去“系统配置”中检查一下是否正确';
        $this->html(Alert::make($info, '注意事项')->warning());
        $this->disableResetButton();
        $this->textarea('product_ids', '准备合成多规格的商品ID')->attribute('id', 'batch-ids'); //批量选择的行的id通过隐藏元素 提交时一并传递过去
    }

    public function handle(array $input)
    {
        $productIds = $input['product_ids'];
        $productIdsArray = clean_ids($productIds, true);
        if (! $productIdsArray) {
            return $this->response()->error('请选择至少一个商品')->refresh();
        }
        $productList = ShopProduct::whereIn('id', $productIdsArray)->select(['channel', 'id', 'sku_spec'])->get()->toArray();
        $channels = array_column($productList, 'channel');
        $channelCheck = count(array_unique($channels)) == 1;
        if (! $channelCheck) {
            return $this->response()->error('您所选择的商品来自不同小程序，无法创建多规格');
        }
        $channel = $channels[0];
        $configName = 'shopProductSceneConfig_'.$channel;
        $configInfo = SysConfig::where('name', $configName)->first();
        if (! $configInfo) {
            return $this->response()->error("此小程序还未在“系统配置”中创建多规格商品项【{$configName}】");
        }
        $configValue = $configInfo->value;
        $configValue = json_decode($configValue, true);
        ksort($configValue);
        $newValue = [];
        foreach ($productList as $item) {
            $newValue['specList']['a'.$item['id']] = $item['sku_spec'];
        }
        $configValue[] = $newValue;
        $configInfo->value = json_encode($configValue, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
        $result = $configInfo->save();

        if (! $result) {
            return $this->response()->error('添加多规格商品配置失败')->refresh();
        }
        $key = SystemConfigService::$SYSTEM_CONFIG_NAME.$configName;
        app('redis')->setex($key, 3600, json_encode($configValue));

        return $this->response()->success('添加多规格商品配置失败')->refresh();
    }
}
