<?php

namespace App\Admin\Actions\Coupon;

use App\Jobs\CheckCouponByLog;
use App\Jobs\CheckCouponLog;
use Carbon\Carbon;
use Encore\Admin\Actions\Action;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Schema;

class RefreshPAOrder extends Action
{
    public $name = '刷新平安订单id';

    protected $selector = '.refresh-order';

    public function handle(Request $request): \Encore\Admin\Actions\Response
    {
        $month = $request->month;
        $month = Carbon::parse($month)->format('Ym');
        $table = 'api_log_'.$month;
        
        if (! Schema::hasColumn($table, 'coupon_no')) {
            Schema::table($table, function (Blueprint $table) {
                $table->string('coupon_no')->after('out_source')->nullable();
            });
        }

        CheckCouponLog::dispatch($table);
        CheckCouponByLog::dispatch($table, 10);

        return $this->response()->success('正在获取数据，请等待片刻后刷新页面查看！')->refresh();
    }

    public function form()
    {
        $this->date('month', '月份')->format('YYYY-MM');
    }

    public function html()
    {
        return <<<HTML
        <a class="btn btn-sm btn-default refresh-order "><i class="fa fa-refresh"></i>  刷新平安订单id</a>
HTML;
    }
}
