<?php

namespace Modules\Configuration;

use Illuminate\Support\Facades\Artisan;
use Nwidart\Modules\Facades\Module as ModuleManager;

class Configuration
{
    protected static string $mainTitle = '参数配置管理';

    /**
     * Notes   : 模块初始化要做的一些操作
     */
    public static function install()
    {
        Artisan::call('migrate', [
            '--path' => 'modules/Configuration/Database/Migrations',
        ]);

        self::createAdminMenu();
    }

    /**
     * Notes   : 卸载模块的一些操作
     */
    public static function uninstall()
    {
        $menu = config('admin.database.menu_model');

        $main = $menu::where('title', self::$mainTitle)->first();

        $main->delete();
    }

    /**
     * 根据模块配置情况创建是否需要配置菜单
     */
    protected static function createAdminMenu()
    {
        $menu = config('admin.database.menu_model');

        $main    = $menu::create([
            'parent_id' => 0,
            'order'     => 50,
            'title'     => self::$mainTitle,
            'icon'      => 'fa-bars',
        ]);
        $modules = ModuleManager::toCollection();
        $data    = [];
        $i       = 1;
        foreach ($modules as $module) {
            $need = $module->get('config', false);
            if ($need) {
                $name = $module->get('configName', '');
                if (! $name) {
                    $name = $module->getName();
                }
                $alias  = $module->getAlias();
                $data[] = [
                    'order' => $i,
                    'title' => $name.'配置',
                    'icon'  => 'fa-bars',
                    'uri'   => 'configurations/'.$alias,
                ];
                $i++;
            }
        }
        if (count($data) > 0) {
            $main->children()->createMany($data);
        }
    }
}
