<?php

namespace app\admin\model;

use app\common\constants\MenuConstant;
use app\common\model\TimeModel;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Model;

class SystemMenu extends TimeModel
{
    public static array $menuTypeList = [
        'system' => '系统管理',
        'mall'   => '商城管理',
        'article'   => '文章管理',
    ];

    protected function getOptions(): array
    {
        return [
            'deleteTime' => 'delete_time',
        ];
    }

    public static function onBeforeUpdate(Model $model): void
    {
        $model->system = 0; // 系统添加

    }

    /**
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws DataNotFoundException
     */
    public static function getPidMenuList(): array
    {
        $list = self::field('id,pid,title')->where([
            ['pid', '<>', MenuConstant::HOME_PID],
            ['status', '=', 1],
        ])->select()->toArray();

        $pidMenuList = self::buildPidMenu(0, $list);
        return array_merge([[
            'id'    => 0,
            'pid'   => 0,
            'title' => '顶级菜单',
        ]], $pidMenuList);
    }

    protected static function buildPidMenu($pid, $list, $level = 0): array
    {
        $newList = [];
        foreach ($list as $vo) {
            if ($vo['pid'] == $pid) {
                $level++;
                foreach ($newList as $v) {
                    if ($vo['pid'] == $v['pid'] && isset($v['level'])) {
                        $level = $v['level'];
                        break;
                    }
                }
                $vo['level'] = $level;
                if ($level > 1) {
                    $repeatString = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
                    $markString   = str_repeat("{$repeatString}├{$repeatString}", $level - 1);
                    $vo['title']  = $markString . $vo['title'];
                }
                $newList[] = $vo;
                $childList = self::buildPidMenu($vo['id'], $list, $level);
                !empty($childList) && $newList = array_merge($newList, $childList);
            }

        }
        return $newList;
    }

    public static function refreshMenu($nodeList): void
    {
        $nodeList = array_filter($nodeList, function ($item) {
            return $item['type'] == 1;
        });
        $menuList = array_map(function ($item) {
            return "{$item['node']}/index";
        }, $nodeList);

        if (!empty($menuList)) {
            $hasMenu        = (new self())->whereIn('href', $menuList)->column('href');
            $needInsertMenu = array_diff($menuList, $hasMenu);
            $insertNode     = array_filter($nodeList, function ($item) use ($needInsertMenu) {
                return in_array("{$item['node']}/index", $needInsertMenu);
            });
            $data           = [];
            foreach ($insertNode as $vo) {
                $pidText = explode('.', $vo['node']);
                if (isset($pidText[0]) && self::$menuTypeList[$pidText[0]]) {
                    $pidMenuId = (new self())->where([
                        'title' => self::$menuTypeList[$pidText[0]],
                        'pid'   => 0,
                    ])->value('id');
                    if (empty($pidMenuId)) {
                        $pidMenuId = (new self())->insertGetId([
                            'title'  => self::$menuTypeList[$pidText[0]],
                            'href'   => '',
                            'icon'   => 'fa fa-list',
                            'pid'    => 0,
                            'status' => 1,
                            'system' => 0, // 系统添加
                            'create_time' => time(),
                        ]);
                    }
                    $data[] = [
                        'title'  => $vo['title'],
                        'href'   => "{$vo['node']}/index",
                        'icon'   => 'fa fa-list',
                        'target' => '_self',
                        'pid'    => $pidMenuId,
                        'status' => 1,
                        'system' => 1, // 系统添加
                        'create_time' => time(),
                    ];
                }

            };
            if (count($data) > 0) (new self())->insertAll($data);
            self::getPidMenuList(); // 刷新菜单缓存
        }
    }

}