<?php

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

use Encore\Admin\Actions\Response;
use Encore\Admin\Actions\RowAction;
use Exception;
use Illuminate\Http\Request;
use Modules\User\Models\Identity;
use Modules\User\Models\Order;
use Modules\User\Models\User;

class JoinIdentity extends RowAction
{

    public $name = '加入身份';

    public function handle(User $user, Request $request): Response
    {
        try {
            $identity_id = $request->join_identity_id;
            $remark      = $request->remark;
            $identity    = Identity::find($identity_id);
            $price       = $identity->getCondition('price', '0');

            $data = [
                'user_id'     => $user->id,
                'identity_id' => $identity_id,
                'year'        => 1,
                'type'        => 1,
                'stock'       => $identity->stock,
                'name'        => '',
                'card_no'     => '',
                'cover'       => '',
                'state'       => Order::STATE_INIT,
                'price'       => $price,
            ];

            $order = Order::create($data);
            $order->pay();

            return $this->response()->success('加入身份成功')->refresh();
        } catch (Exception $e) {
            return $this->response()->error($e->getMessage())->refresh();
        }
    }

    public function form(User $user)
    {
        $userIdentity = $user->identityFirst();

        $identities = Identity::where('order', '>', $userIdentity->order)->pluck('name', 'id');

        $this->select('join_identity_id', '加入身份')
            ->options($identities)
            ->required();
        $this->text('remark', '加入备注');
        $this->confirm('确认加入该身份？');
    }

}