<?php

namespace App\Admin\Actions\Coupon;

use App\Models\Coupon;
use App\Models\User;
use Encore\Admin\Actions\Action;
use Illuminate\Http\Request;

class Batch extends Action
{

    public    $name     = '批量打款';

    protected $selector = '.import-post';

    public function handle(Request $request)
    {
        $user_id = $request->user_id;
        $date    = $request->date;
        $list    = Coupon::where('user_id', $user_id)->whereDate('created_at', $date)->where('status', 2)->get();
        if ($list->isEmpty()) {
            return $this->response()->error('打款失败！没有可处理的数据')->refresh();
        }

        $success = $error = 0;
        foreach ($list as $key => $coupon) {
            $res = $coupon->sendMoney();
            if ($res === true) {
                $success++;
            } else {
                $error++;
            }
        }

        return $this->response()->success("处理完成，成功：{$success}条，失败：{$error}条")->refresh();
    }

    public function form()
    {
        $users = User::query()
                     ->whereHas('identity', function ($query) {
                         $query->where('identity_id', 1);
                     })
                     ->get()
                     ->pluck('nickname', 'id');

        $this->select('user_id', '渠道')->options($users)->required();
        // 时间日期选择
        $this->date('date', '核销日期')->required();
    }

    public function html()
    {
        return <<<HTML
        <a class="btn btn-sm btn-default import-post"><i class="fa fa-Yuan"></i>批量打款</a>
HTML;
    }

}
