<?php

namespace Modules\User\Http\Controllers\Admin\Actions;

use Encore\Admin\Actions\Action;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Modules\User\Models\User;
use Modules\User\Models\UserInvite;

class AllotCard extends Action
{
    protected $selector = '.report-posts';

    public function handle(Request $request)
    {
        $request->validate([
            'startNum' => 'required|integer|min:1|lte:endNum',
            'endNum'   => 'required|integer|min:1',
        ], [
            'startNum.required' => '开始号码必须填写',
            'startNum.integer'  => '开始号码必须是整数',
            'startNum.min'      => '开始号码最小为1',
            'startNum.lte'      => '开始号码要小于结束号码',
            'endNum.required'   => '结束号码必须填写',
            'endNum.integer'    => '结束号码必须是整数',
            'endNum.min'        => '结束号码最小为1',
        ]);

        $response = $this->response();
        $startNum = $request->startNum ?: 0;
        $endNum   = $request->endNum ?: 0;
        $user_id  = $request->user_id;


//        $startNum = sprintf("%'.08d", $startNum);
//        $endNum   = sprintf("%'.08d", $endNum++);


        $isActive = UserInvite::whereBetween('id', [$startNum, $endNum])->where('status', '!=', 1)->value('code');
        if ($isActive) {
            $response->status = false;
            return $response->error($isActive.'不可分配');
        }

        UserInvite::whereBetween('id', [$startNum, $endNum])->update([
            'user_id' => $user_id,
            'status'  => UserInvite::STATUS_ALLOT,
        ]);

        return $response->success('卡分配完毕')->refresh();
    }

    public function form()
    {
        $users = User::leftJoin('user_infos as info', 'users.id', '=', 'info.user_id')
//            ->whereHas('identities', function ($q) {
//                $q->where('id', 6);
//            })
            ->select('id', DB::raw('CONCAT(username, " [", info.nickname, "]") as text'))
            ->pluck('text', 'id');

        $this->select('user_id', '会员')
            ->options($users)
            ->required();
        $this->text('startNum', '开始')->rules('required|integer|min:1');
        $this->text('endNum', '结束')->rules('required|integer|min:1');

    }

    public function html()
    {
        return "<a class='report-posts btn btn-sm btn-danger'><i class='fa fa-info-circle'></i>分配激活码</a>";
    }
}
