<?php

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

use Encore\Admin\Actions\Response;
use Encore\Admin\Actions\RowAction;
use Exception;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Modules\User\Models\Identity;
use Modules\User\Models\IdentityLog;

class RemoveIdentity extends RowAction
{

    public $name = '移除身份';

    public function handle(Model $user, Request $request): Response
    {
        try {
            $identity_id = $request->remove_identity_id;
            $remark      = $request->remark;
            $user->removeIdentity($identity_id, 'System', [
                'remark' => $remark,
            ]);

            $defaultIdentity = Identity::where('default', 1)->first();
            if ($defaultIdentity) {
                $user->joinIdentity($defaultIdentity->id, IdentityLog::CHANNEL_SYSTEM);
            }

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

    public function form(Model $model)
    {
        $this->select('remove_identity_id', '移除身份')
            ->options(Identity::whereIn('id', $model->identities()->get()->pluck('id'))
                ->pluck('name', 'id'))
            ->required();
        $this->text('remark', '移除说明');
        $this->confirm('确认移除该身份？');
    }

}