<?php

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

use App\Service\Common\CommonAppConfigService;
use App\Service\Shop\ShopPointService;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;

class AddPointForm extends Form implements LazyRenderable
{
    use LazyWidget;

    public function form()
    {
        $this->textarea('user_ids', '用户ID|支付宝UID')->placeholder('如：2200010106,2088702902958383')->help('用户ID或者支付宝UID，逗号等隔开，可以混填，自动识别')->required(); //批量选择的行的id通过隐藏元素 提交时一并传递过去
        $appMap = CommonAppConfigService::getBrandCodeNameMap();
        $this->select('channel', '出资小程序')->placeholder('请选择用哪个小程序赠送积分')->options($appMap)->required();
        $this->number('point', '赠送积分')->min(1)->max(1000)->default(100)->help('单个循环赠送积分不能超过1000');
        $this->number('count', '赠送次数')->min(1)->max(20)->default(1)->help('最多循环20次');
    }

    public function handle(array $input)
    {
        $userIds = $input['user_ids'];
        $point = $input['point'];
        $channel = $input['channel'];
        $count = $input['count'];
        if ($point > 1000 || $point < 1) {
            return $this->response()->error('每次赠送积分需在1到1000分之间');
        }
        if ($count > 20 || $count < 1) {
            return $this->response()->error('循环赠送次数不能超过20');
        }

        $userIds = clean_ids($userIds, true);

        if (! $userIds) {
            return $this->response()->error('至少填写一个用户ID|支付宝UID');
        }
        for ($i = 1; $i <= $count; $i++) {
            foreach ($userIds as $userId) {
                ShopPointService::customSendPoint($channel, $userId, $point);
            }
        }

        return $this->response()->alert(true)->success('赠送积分成功')->refresh();

    }
}
