<?php

namespace App\Admin\Controllers;

use App\Models\Module;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Grid;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Artisan;
use Nwidart\Modules\Facades\Module as ModuleManager;

class ModuleController extends AdminController
{

    protected $title = '模块管理';

    protected function grid(): Grid
    {
        $grid = new Grid(new Module());

        $grid->disableBatchActions();
        $grid->disableFilter();
        $grid->disableCreateButton();
        $grid->disablePagination();
        $grid->disableActions();

        $grid->column('name', '模块名称');
        $grid->column('alias', '别名');
        $grid->column('version', '版本');
        $grid->column('author', '作者');
        $grid->column('description', '模块简介');
        $grid->column('enabled', '状态')->bool();
        $grid->column('id', '操作')->display(function () {
            if ($this->enabled) {
                return sprintf('<a href="%s">%s</a>', route('admin.module.disable', $this->name), '禁用');
            } else {
                return sprintf('<a href="%s">%s</a>', route('admin.module.enable', $this->name), '启用');
            }
        });

        return $grid;
    }

    /**
     * Notes   : 禁用模块
     * @Date   : 2021/3/11 1:13 下午
     * @Author : < Jason.C >
     * @param $name
     * @return \Illuminate\Http\RedirectResponse
     */
    public function disable($name): RedirectResponse
    {
        try {
            $module = ModuleManager::find($name);

            $module->disable();

            $class = sprintf('\\%s\\%s\\%s', config('modules.namespace'), $module->getName(), $module->getName());

            if (class_exists($class)) {
                call_user_func([$class, 'uninstall']);
            }

            admin_success('Success', $name . '模块禁用成功');
        } catch (\Exception $exception) {
            admin_error('Error', $exception->getMessage());
        }

        return back();
    }

    /**
     * Notes   : 启用模块
     * @Date   : 2021/3/11 1:13 下午
     * @Author : < Jason.C >
     * @param $name
     * @return \Illuminate\Http\RedirectResponse
     */
    public function enable($name): RedirectResponse
    {
        try {
            $module = ModuleManager::find($name);

            $module->enable();

            $class = sprintf('\\%s\\%s\\%s', config('modules.namespace'), $module->getName(), $module->getName());

            if (class_exists($class)) {
                call_user_func([$class, 'install']);
            }

            admin_success('Success', $name . '模块启用成功');
        } catch (\Exception $exception) {
            admin_error('Error', $exception->getMessage());
        }

        return back();
    }

}